How do I remove a directory that is not empty?
✔ Recommended Answer
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);}
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}
Source: stackoverflow.com
Answered By: John Kugelman
To remove a directory in PHP that is not empty, you can use the recursive directory removal function rmdir_recursive()
which deletes all files and subdirectories in the specified directory recursively.
Here is an example code snippet to remove a directory that is not empty in PHP:
phpfunction rmdir_recursive($dir) {
$files = array_diff(scandir($dir), array('.', '..'));
foreach ($files as $file) {
$path = $dir . '/' . $file;
if (is_dir($path)) {
rmdir_recursive($path);
} else {
unlink($path);
}
}
return rmdir($dir);
}
// Example usage: remove the directory "/path/to/dir"
if (is_dir('/path/to/dir')) {
rmdir_recursive('/path/to/dir');
}
In this example, the rmdir_recursive()
function takes a directory path as its parameter, and recursively deletes all files and subdirectories in the specified directory. If the directory is successfully emptied, the function then removes the directory itself using the rmdir()
function.
To use the function, you can call it with the path of the directory you want to remove, like in the example usage code above.
Note that it is important to be careful when deleting directories and their contents, as this operation is not reversible and can result in permanent data loss.
Comments
Post a Comment