PHP remove directory recursively
Removing a directory with PHP is very easy and can be done with the rmdir function. If there are still files within the directory or other directories within the directory we are trying to delete, then the rmdir function does not work. The directory being removed must be empty. Therefore to remove the directory and all files under that directory with PHP, we need a smarter script.
Below is a small script I use to delete a directory and all the files under it.
class File {
static public function removeDirectoryRecursive($directory) {
$directory = substr($directory, -1) == '/' ? substr($directory, 0, -1) : $directory;
$files = scandir($directory);
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
$fileFullPath = $directory . '/' . $file;
if (is_dir($fileFullPath)) {
File::removeDirectoryRecursive($fileFullPath);
} else {
unlink($fileFullPath);
}
}
}
rmdir($directory);
}
}
// removing a directory
File::removeDirectoryRecursive($directory);
This is just a simple method that works by removing the directory that you send to it and also all the directories and files under it. Feel free to add more methods to this class and also make the removeDirectoryRecursive method a little more robust. We could return true if it was successful and maybe throw an exception if we didn't have the permissions to delete a file.