Recursively Delete A Non-Empty Directory With PHP5
Posted on November 26th, 2008 in PHP | 1 Comment »
There are bunches of examples on how to delete non-empty directories in PHP but none of the examples that I’ve seen take advantage of PHP5’s RecursiveDirectoryIterator which makes this an almost trivial task. If you haven’t already, please check out the SPL Standard PHP Library Classes. I keep a class of static utility functions and here is my function to delete non-empty directories recursively.
public static function deleteDir($dir) {
$iterator = new RecursiveDirectoryIterator($dir);
foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) {
if ($file->isDir()) {
rmdir($file->getPathname());
} else {
unlink($file->getPathname());
}
}
rmdir($dir);
}
Please note the RecursiveIteratorIterator::CHILD_FIRST parameter. Without that the listing will not be in the correct order. As you iterate along you will end up trying to delete directories before they are empty. This CHILD_FIRST parameter was added with PHP 5.1 so make sure you have at least that version installed before using this technique.
One Response
Any idea how this handles symlinks? I’ve seen quite a few recursive delete functions that remove symlinked directories without checking (IMO the link should be removed, but not the directory it’s linking to).