I am trying to remove a directory with rmdir
, but I received the 'Directory not empty' message, because it still has files in it.
What function can I use to remove a directory with all the files in it as well?
I am trying to remove a directory with rmdir
, but I received the 'Directory not empty' message, because it still has files in it.
What function can I use to remove a directory with all the files in it as well?
There is no built-in function to do this, but see the comments at the bottom of http://us3.php.net/rmdir. A number of commenters posted their own recursive directory deletion functions. You can take your pick from those.
Here's one that looks decent:
function deleteDirectory($dir) {
if (!file_exists($dir)) {
return true;
}
if (!is_dir($dir)) {
return unlink($dir);
}
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') {
continue;
}
if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
return false;
}
}
return rmdir($dir);
}
Edit: You could just invoke rm -rf
if you want to keep things simple. That does make your script UNIX-only, so beware of that. If you go that route I would try something like:
function deleteDirectory($dir) {
system('rm -rf ' . escapeshellarg($dir), $retval);
return $retval == 0; // UNIX commands return zero on success
}