phprecursiondelete-directory

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


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


Solution

  • The user-contributed section in the manual page of rmdir contains a decent implementation:

     function rrmdir($dir) { 
       if (is_dir($dir)) { 
         $objects = scandir($dir);
         foreach ($objects as $object) { 
           if ($object != "." && $object != "..") { 
             if (is_dir($dir. DIRECTORY_SEPARATOR .$object) && !is_link($dir."/".$object))
               rrmdir($dir. DIRECTORY_SEPARATOR .$object);
             else
               unlink($dir. DIRECTORY_SEPARATOR .$object); 
           } 
         }
         rmdir($dir); 
       } 
     }