01 <?php
02
03 /*
04
05 recursive_remove_directory( directory to delete, empty )
06 expects path to directory and optional TRUE / FALSE to empty
07 of course PHP has to have the rights to delete the directory
08 you specify and all files and folders inside the directory
09
10 */
11
12 function recursive_remove_directory($directory, $empty=FALSE)
13 {
14 // if the path has a slash at the end we remove it here
15 if(substr($directory,-1) == '/')
16 {
17 $directory = substr($directory,0,-1);
18 }
19
20 // if the path is not valid or is not a directory ...
21 if(!file_exists($directory) || !is_dir($directory))
22 {
23 // ... we return false and exit the function
24 return FALSE;
25
26 // ... if the path is not readable
27 }elseif(!is_readable($directory))
28 {
29 // ... we return false and exit the function
30 return FALSE;
31
32 // ... else if the path is readable
33 }else{
34
35 // we open the directory
36 $handle = opendir($directory);
37
38 // and scan through the items inside
39 while (FALSE !== ($item = readdir($handle)))
40 {
41 // if the filepointer is not the current directory
42 // or the parent directory
43 if($item != '.' && $item != '..')
44 {
45 // we build the new path to delete
46 $path = $directory.'/'.$item;
47
48 // if the new path is a directory
49 if(is_dir($path))
50 {
51 // we call this function with the new path
52 recursive_remove_directory($path);
53
54 // if the new path is a file
55 }else{
56 // we remove the file
57 unlink($path);
58 }
59 }
60 }
61 // close the directory
62 closedir($handle);
63
64 // if the option to empty is not set to true
65 if($empty == FALSE)
66 {
67 // try to delete the now empty directory
68 if(!rmdir($directory))
69 {
70 // return false if not possible
71 return FALSE;
72 }
73 }
74 // return success
75 return TRUE;
76 }
77 }
78
79 // examples
80 // to use this function to totally remove a directory, write:
81 // recursive_remove_directory('path/to/directory/to/delete');
82
83 // to use this function to empty a directory, write:
84 // recursive_remove_directory('path/to/full_directory',TRUE);
85
86 ?>