删除目录中的文件吗? [英] Delete directory with files in it?
本文介绍了删除目录中的文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道,删除其中包含所有文件的目录的最简单方法是什么?
I wonder, what's the easiest way to delete a directory with all its files in it?
我正在使用rmdir(PATH . '/' . $value);
删除文件夹,但是,如果其中有文件,我将无法删除它.
I'm using rmdir(PATH . '/' . $value);
to delete a folder, however, if there are files inside of it, I simply can't delete it.
推荐答案
现在至少有两个选项.
-
在删除文件夹之前,删除其所有文件和文件夹(这意味着递归!).这是一个示例:
Before deleting the folder, delete all its files and folders (and this means recursion!). Here is an example:
public static function deleteDir($dirPath) {
if (! is_dir($dirPath)) {
throw new InvalidArgumentException("$dirPath must be a directory");
}
if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
$dirPath .= '/';
}
$files = glob($dirPath . '*', GLOB_MARK);
foreach ($files as $file) {
if (is_dir($file)) {
self::deleteDir($file);
} else {
unlink($file);
}
}
rmdir($dirPath);
}
如果您使用的是5.2+,则可以使用RecursiveIterator来实现,而无需自己实现递归:
And if you are using 5.2+ you can use a RecursiveIterator to do it without implementing the recursion yourself:
$dir = 'samples' . DIRECTORY_SEPARATOR . 'sampledirtree';
$it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($it,
RecursiveIteratorIterator::CHILD_FIRST);
foreach($files as $file) {
if ($file->isDir()){
rmdir($file->getRealPath());
} else {
unlink($file->getRealPath());
}
}
rmdir($dir);
这篇关于删除目录中的文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文