Search code examples
phpdirectoryrmdir

In PHP how do I recursively remove all folders that aren't empty?


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

I need to recursively delete a directory and subdirectories that aren't empty. I can't find any useful class or function to solve this problem.

In advance thanks for your answers.


Solution

  • From the first comment in the official documentation.

    http://php.net/manual/en/function.rmdir.php

    <?php
    
     // When the directory is not empty:
     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);
       }
     }
    
    ?>
    

    Edited rmdir to rrmdir to correct typo from obvious intent to create recursive function.