Add/Remove Directories

June 4th, 2008

I just wanted to share with you 2 small, yet very useful, functions that you could use in PHP: dir_create and dir_remove. The name of the function gives away the purpose of what they will do. From time to time, I will get stuck with “Why is PHP not creating the directory?” or “Why isn’t PHP removing the directory completely?”, and that is where these two functions come into play to help you with those pesky little simple questions. Here are the functions:

[php]
function dir_create($path = ”, $mode = 0777) {
if($path === ”) { return false; }
$paths = explode(“/”, $path);
$ph = ”;
for($i = 0; $i < count($paths); $i++) { $ph .= $paths[$i] . "/"; if(!is_dir($ph)) { $m = umask(0); mkdir($ph, $mode); umask($m); } } return true; } function dir_remove($path = '') { if($path === '') { return false; } $path .= (substr($path, -1) !== "/") ? "/" : ''; $dh = opendir($path); while($file = readdir($dh)) { if(!in_array($file, array(".", ".."))) { if(!is_dir($path . $file)) { unlink($path . $file); } else { dir_remove($path . $file); } } } closedir($dh); rmdir($path); return true; } [/php] Directory Create Explanation 1. Create the function dir_create
2. If no path was sent, return false
3. Use the explode() function to hold the paths into an array. This will help us loop through each directory and create the directory if it doesn’t exist. So we can create more than 1 directory at one time
4. Declare a variable called $ph, short for “path holder”. This holds the string of the paths when we loop through $paths array
5. Loop through the $path array
6. Add an / (forward slash) to the $ph variable
7 – 11. Check to see if the directory exists, if it doesn’t create the directory with the past mode, default is 0777
12. Close the for loop
13. Return true
14. Close the dir_create function

Directory Remove Explanation
16. Create the function dir_remove
17. If no path was sent, return false
18. Add the / (forward slash) at the end of the $path if it doesn’t already contain one
19. Open the directory
20. Begin reading the files through the directory
21 – 27. A couple if statements to check what the $file is. If the file is not a directory, we unlink it, or if it is a directory, we execute the dir_remove function again to remove files within the directory. So if decide to remove everything in our root directory, we can with this – so be careful on how this function is used!
28. Close the while loop
29. Close the directory
30. Remove the directory it self
31. Return true
32. Close the dir_remove function

PHP > Website

Leave a Reply

Enter code snippets inside of <pre> and </pre>