tags:

views:

81

answers:

4

How do I delete a directory and its entire contents (files+sub dirs) in PHP?

+2  A: 

Have you tried the first note in the manual page of rmdir?

 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); 
   } 
 }
Artefacto
Yuck, I'm sure that can be re-factored into something nice using DirectoryIterator.
The Pixel Developer
@The Pixel Developer - I added [an answer](http://stackoverflow.com/questions/3338123/how-do-i-recursively-delete-a-directory-and-its-entire-contents-filessub-dirs/3352564#3352564) showing that.
salathe
+3  A: 

Or better do a shell_exec for rm -R

Ankit Jain
wont work on windows
Gordon
how about `DEL /S folder_name` for Windows
Ankit Jain
A: 

The above piece of code is perfectly written. It works fine from the browser if the file and folder have the deletion rights.

I successfully executed the code from the command prompt using sudo. Here is the command:

$ sudo php -e deleteRecursively.php 
Prashant Agarwal
+3  A: 

Building on The Pixel Developer's comment, a snippet using the SPL might look like:

$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
    RecursiveIteratorIterator::CHILD_FIRST
);

foreach ($files as $fileinfo) {
    $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
    $todo($fileinfo->getRealPath());
}

Note: It does no sanity checking and makes use of the SKIP_DOTS flag introduced with the FilesystemIterator in PHP 5.3.0. Of course, the $todo could be an if/else. The important point is that CHILD_FIRST is used to iterate over the children (files) first before their parent (folders).

salathe