我想知道,删除一个包含所有文件的目录最简单的方法是什么?
我使用的是rmdir(PATH。“/”。美元价值);要删除一个文件夹,但是,如果里面有文件,我根本不能删除它。
我想知道,删除一个包含所有文件的目录最简单的方法是什么?
我使用的是rmdir(PATH。“/”。美元价值);要删除一个文件夹,但是,如果里面有文件,我根本不能删除它。
当前回答
这里有一个简单的解决办法
$dirname = $_POST['d'];
$folder_handler = dir($dirname);
while ($file = $folder_handler->read()) {
if ($file == "." || $file == "..")
continue;
unlink($dirname.'/'.$file);
}
$folder_handler->close();
rmdir($dirname);
其他回答
一点点修改alcuadrado的代码- glob不看到文件名从点像.htaccess,所以我使用scandir和脚本删除本身-检查__FILE__。
function deleteDir($dirPath) {
if (!is_dir($dirPath)) {
throw new InvalidArgumentException("$dirPath must be a directory");
}
if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
$dirPath .= '/';
}
$files = scandir($dirPath);
foreach ($files as $file) {
if ($file === '.' || $file === '..') continue;
if (is_dir($dirPath.$file)) {
deleteDir($dirPath.$file);
} else {
if ($dirPath.$file !== __FILE__) {
unlink($dirPath.$file);
}
}
}
rmdir($dirPath);
}
类似Playnox的解决方案,但有优雅的内置DirectoryIterator:
function delete_directory($dirPath){
if(is_dir($dirPath)){
$objects=new DirectoryIterator($dirPath);
foreach ($objects as $object){
if(!$object->isDot()){
if($object->isDir()){
delete_directory($object->getPathname());
}else{
unlink($object->getPathname());
}
}
}
rmdir($dirPath);
}else{
throw new Exception(__FUNCTION__.'(dirPath): dirPath is not a directory!');
}
}
windows:
system("rmdir ".escapeshellarg($path) . " /s /q");
我更喜欢这个,因为它仍然在成功时返回TRUE,失败时返回FALSE,而且它还防止了一个错误,即一个空路径可能会尝试删除'/*'中的所有内容!!:
function deleteDir($path)
{
return !empty($path) && is_file($path) ?
@unlink($path) :
(array_reduce(glob($path.'/*'), function ($r, $i) { return $r && deleteDir($i); }, TRUE)) && @rmdir($path);
}
这里有一个完美的解决方案:
function unlink_r($from) {
if (!file_exists($from)) {return false;}
$dir = opendir($from);
while (false !== ($file = readdir($dir))) {
if ($file == '.' OR $file == '..') {continue;}
if (is_dir($from . DIRECTORY_SEPARATOR . $file)) {
unlink_r($from . DIRECTORY_SEPARATOR . $file);
}
else {
unlink($from . DIRECTORY_SEPARATOR . $file);
}
}
rmdir($from);
closedir($dir);
return true;
}