phprmdir

Delete directory with files in it?


I wonder, what's the easiest way to delete a directory with all its files in it?

I'm using rmdir(PATH . '/' . $value); to delete a folder, however, if there are files inside of it, I simply can't delete it.


Solution

  • There are at least two options available nowadays.

    1. Before deleting the folder, delete all its files and folders (and this means recursion!). Here is an example:

      function deleteDir(string $dirPath): void {
          if (! is_dir($dirPath)) {
              throw new InvalidArgumentException("$dirPath must be a directory");
          }
          if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
              $dirPath .= '/';
          }
          $files = glob($dirPath . '*', GLOB_MARK);
          foreach ($files as $file) {
              if (is_dir($file)) {
                  deleteDir($file);
              } else {
                  unlink($file);
              }
          }
          rmdir($dirPath);
      }
      
    2. And if you are using 5.2+ you can use a RecursiveIterator to do it without implementing the recursion yourself:

      function removeDir(string $dir): void {
          $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
          $files = new RecursiveIteratorIterator($it,
                       RecursiveIteratorIterator::CHILD_FIRST);
          foreach($files as $file) {
              if ($file->isDir()){
                  rmdir($file->getPathname());
              } else {
                  unlink($file->getPathname());
              }
          }
          rmdir($dir);
      }