Thursday, February 28, 2008

How to delete all files and subfolders in a directory with PHP

If you have access to the shell or SSH, you can type in:

rm -fr /path/to/dir/
to delete all files and folders in a directory. However, if you don't have shell access, you may want to try running a system command via php.
echo exec('rm -fr /path/to/dir/');
If your PHP is not allowed to execute system commands, then you'll have to suffice to the PHP functions for directory and file traversal and manipulation.

In my last post I talked about installing Joomla on a remote server. Sometimes you make a few mistakes, and want to remove a whole directory and all files in it. If you don't have the benefit of a shell or shell command execution with PHP, you have to write your own functions to delete the non empty directory.

Deletes all subfolders and files in a directory recursively

/**
 * Deletes a directory and all files and folders under it
 * @return Null
 * @param $dir String Directory Path
 */
function rmdir_files($dir) {
 $dh = opendir($dir);
 if ($dh) {
  while($file = readdir($dh)) {
   if (!in_array($file, array('.', '..'))) {
    if (is_file($dir.$file)) {
     unlink($dir.$file);
    }
    else if (is_dir($dir.$file)) {
     rmdir_files($dir.$file);
    }
   }
  }
  rmdir($dir);
 }
}

This is quite a nasty function. You want to handle it with care. Make sure you don't delete any directories that you do not intend to delete. It will attempt to remove the whole directory, and all files in it. It does no error checking apart from making sure a directory handle was opened successfully for reading.

No comments: