How to delete a folder with other files and folders inside with PHP [duplicate]
Possible Duplicate:
A recursive remove directory function for PHP?
With PHP
I want to know the easiest way for delete a folder with files and folders inside.
This trick from the PHP docs is pretty cool:
function rrmdir($path)
{
return is_file($path)?
@unlink($path):
array_map('rrmdir',glob($path.'/*'))==@rmdir($path)
;
}
It exploits array_map
, which calls the given function on an array of results. It's also cross-platform.
system("rm -fr $foldername");
It only works on unix though, but it is easy.
This recursive function has been posted as a comment on the rmdir() function reference page:
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);
}
}
This was posted here http://www.php.net/manual/en/function.rmdir.php
if(!file_exists($directory) || !is_dir($directory)) {
return false;
} elseif(!is_readable($directory)) {
return false;
} else {
$directoryHandle = opendir($directory);
while ($contents = readdir($directoryHandle)) {
if($contents != '.' && $contents != '..') {
$path = $directory . "/" . $contents;
if(is_dir($path)) {
deleteAll($path);
} else {
unlink($path);
}
}
}
closedir($directoryHandle);
if($empty == false) {
if(!rmdir($directory)) {
return false;
}
}
return true;
}
}
精彩评论