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

Itay Moav -Malimovka picture Itay Moav -Malimovka · Jul 26, 2010 · Viewed 123.4k times · Source

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

Answer

Artefacto picture Artefacto · Jul 26, 2010

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); 
   } 
 }