Page 1 of 1

PHP - Delete directory with files in it

Posted: 16 Jan 2015, 07:25
by PloMar
What's the best 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.

PHP - Delete directory with files in it

Posted: 16 Jan 2015, 07:35
by Admin
This function will allow you to delete any folder (as long as it's writable) and it's files and subdirectories:

Code: Select all

function deleteDir($path) {
  if(is_dir($path) === true) {
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::CHILD_FIRST);
    foreach ($files as $file) {
      if(in_array($file->getBasename(), array('.', '..')) !== true) {
        if($file->isDir() === true) rmdir($file->getPathName());
        else if (($file->isFile() === true) || ($file->isLink() === true)) unlink($file->getPathname());
      }
    }

    return rmdir($path);
  }
  else if((is_file($path) === true) || (is_link($path) === true)) return unlink($path);

  return false;
}

// Usage
deleteDir('dir/test/');