15

Possible Duplicate:
how to delete a folder with contents using PHP

I know that you can remove a folder that is empty with rmdir. And I know you can clear a folder with the following three lines.

foreach($directory_path as $file) {
       unlink($file);
}

But what if one of the files is actually a sub directory. How would one get rid of that but in an infinite amount like the dual mirror effect. Is there any force delete directory in php?

Thanks

Community
  • 1
  • 1
Jjack
  • 1,276
  • 4
  • 13
  • 20

3 Answers3

49

This function will delete a directory recursively:

function rmdir_recursive($dir) {
    foreach(scandir($dir) as $file) {
        if ('.' === $file || '..' === $file) continue;
        if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file");
        else unlink("$dir/$file");
    }
    rmdir($dir);
}

This one too:

function rmdir_recursive($dir) {
    $it = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
    $it = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
    foreach($it as $file) {
        if ($file->isDir()) rmdir($file->getPathname());
        else unlink($file->getPathname());
    }
    rmdir($dir);
}
Vuong
  • 617
  • 11
  • 26
Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
  • 4
    Actually you can use RecursiveDirectoryIterator::SKIP_DOTS flag to avoid first if statement... – Tomasz Kapłoński Sep 24 '15 at 12:37
  • SKIP_DOTS doesn't exist in the doc, where did you find this? – Eric Nov 04 '15 at 21:46
  • 3
    SKIP_DOTS is referenced here : [FilesystemIterator documentation](http://php.net/manual/fr/filesystemiterator.construct.php). It's herited from parent class `FilesystemIterator`. – Elorfin Aug 20 '16 at 10:13
  • The first function well return an error if the parameter is a correct path but does not exist – utdev Jan 17 '17 at 13:22
9

From PHP rmdir page:

<?php 
 function rrmdir($dir) { 
   if (is_dir($dir)) { 
     $objects = scandir($dir); 
     foreach ($objects as $object) { 
       if ($object != "." && $object != "..") { 
         if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object); 
       } 
     } 
     reset($objects); 
     rmdir($dir); 
   } 
 } 
?>

And

<?php 
function delTree($dir) { 
    $files = glob( $dir . '*', GLOB_MARK ); 
    foreach( $files as $file ){ 
        if( substr( $file, -1 ) == '/' ) 
            delTree( $file ); 
        else 
            unlink( $file ); 
    } 

    if (is_dir($dir)) rmdir( $dir ); 

} 
?>
Paul DelRe
  • 4,003
  • 1
  • 24
  • 26
4
<?php 
 function rrmdir($dir) { 
   if (is_dir($dir)) { 
     $objects = scandir($dir); 
     foreach ($objects as $object) { 
       if ($object != "." && $object != "..") { 
         if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object); 
       } 
     } 
     reset($objects); 
     rmdir($dir); 
   } 
 } 
?>

from PHP's documentation

genesis
  • 50,477
  • 20
  • 96
  • 125