我想知道,删除一个包含所有文件的目录最简单的方法是什么?
我使用的是rmdir(PATH。“/”。美元价值);要删除一个文件夹,但是,如果里面有文件,我根本不能删除它。
我想知道,删除一个包含所有文件的目录最简单的方法是什么?
我使用的是rmdir(PATH。“/”。美元价值);要删除一个文件夹,但是,如果里面有文件,我根本不能删除它。
当前回答
我想通过@Vijit处理符号链接的评论来扩展@alcuadrado的答案。首先,使用getRealPath()。但是,如果你有任何符号链接是文件夹,它会失败,因为它会尝试在链接上调用rmdir -所以你需要额外的检查。
$it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
foreach($files as $file) {
if ($file->isLink()) {
unlink($file->getPathname());
} else if ($file->isDir()){
rmdir($file->getPathname());
} else {
unlink($file->getPathname());
}
}
rmdir($dir);
其他回答
对我来说最好的解决方案
my_folder_delete("../path/folder");
代码:
function my_folder_delete($path) {
if(!empty($path) && is_dir($path) ){
$dir = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS); //upper dirs are not included,otherwise DISASTER HAPPENS :)
$files = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($files as $f) {if (is_file($f)) {unlink($f);} else {$empty_dirs[] = $f;} } if (!empty($empty_dirs)) {foreach ($empty_dirs as $eachDir) {rmdir($eachDir);}} rmdir($path);
}
}
注。记住!不要将空值传递给任何目录删除函数!!(总是备份它们,否则有一天你可能会遇到灾难!!)
我通常用它来删除文件夹中的所有文件:
array_map('unlink', glob("$dirname/*.*"));
然后你就可以做了
rmdir($dirname);
完成工作的简短函数:
function deleteDir($path) {
return is_file($path) ?
@unlink($path) :
array_map(__FUNCTION__, glob($path.'/*')) == @rmdir($path);
}
我在Utils类中使用它,就像这样:
class Utils {
public static function deleteDir($path) {
$class_func = array(__CLASS__, __FUNCTION__);
return is_file($path) ?
@unlink($path) :
array_map($class_func, glob($path.'/*')) == @rmdir($path);
}
}
能力越大责任越大:当你用空值调用这个函数时,它会删除根目录(/)下的文件。为了安全起见,你可以检查path是否为空:
function deleteDir($path) {
if (empty($path)) {
return false;
}
return is_file($path) ?
@unlink($path) :
array_map(__FUNCTION__, glob($path.'/*')) == @rmdir($path);
}
我想通过@Vijit处理符号链接的评论来扩展@alcuadrado的答案。首先,使用getRealPath()。但是,如果你有任何符号链接是文件夹,它会失败,因为它会尝试在链接上调用rmdir -所以你需要额外的检查。
$it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
foreach($files as $file) {
if ($file->isLink()) {
unlink($file->getPathname());
} else if ($file->isDir()){
rmdir($file->getPathname());
} else {
unlink($file->getPathname());
}
}
rmdir($dir);
您可以尝试如下:
/*
* Remove the directory and its content (all files and subdirectories).
* @param string $dir the directory name
*/
function rmrf($dir) {
foreach (glob($dir) as $file) {
if (is_dir($file)) {
rmrf("$file/*");
rmdir($file);
} else {
unlink($file);
}
}
}