PHP - Delete directory with files in it

Discuss coding issues, and scripts related to PHP and MySQL.
PloMar
Posts: 48

PHP - Delete directory with files in it

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.

Admin Posts: 805
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/'); 

Similar Topics