How do I delete a directory and its entire contents (files+sub dirs) in PHP?
views:
81answers:
4
+2
A:
Have you tried the first note in the manual page of rmdir
?
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
Artefacto
2010-07-26 19:11:48
Yuck, I'm sure that can be re-factored into something nice using DirectoryIterator.
The Pixel Developer
2010-07-28 03:49:52
@The Pixel Developer - I added [an answer](http://stackoverflow.com/questions/3338123/how-do-i-recursively-delete-a-directory-and-its-entire-contents-filessub-dirs/3352564#3352564) showing that.
salathe
2010-07-28 11:58:51
A:
The above piece of code is perfectly written. It works fine from the browser if the file and folder have the deletion rights.
I successfully executed the code from the command prompt using sudo. Here is the command:
$ sudo php -e deleteRecursively.php
Prashant Agarwal
2010-07-28 08:59:53
+3
A:
Building on The Pixel Developer's comment, a snippet using the SPL might look like:
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $fileinfo) {
$todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
$todo($fileinfo->getRealPath());
}
Note: It does no sanity checking and makes use of the SKIP_DOTS flag introduced with the FilesystemIterator in PHP 5.3.0. Of course, the $todo
could be an if
/else
. The important point is that CHILD_FIRST
is used to iterate over the children (files) first before their parent (folders).
salathe
2010-07-28 11:58:12