例如,我有一个名为“Temp”的文件夹,我想使用PHP删除或刷新该文件夹中的所有文件。我可以这样做吗?
当前回答
下面是一种使用标准PHP库(SPL)的更现代的方法。
$dir = "path/to/directory";
if(file_exists($dir)){
$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
foreach ( $ri as $file ) {
$file->isDir() ? rmdir($file) : unlink($file);
}
}
其他回答
public static function recursiveDelete($dir)
{
foreach (new \DirectoryIterator($dir) as $fileInfo) {
if (!$fileInfo->isDot()) {
if ($fileInfo->isDir()) {
recursiveDelete($fileInfo->getPathname());
} else {
unlink($fileInfo->getPathname());
}
}
}
rmdir($dir);
}
$dir = 'your/directory/';
foreach(glob($dir.'*.*') as $v){
unlink($v);
}
我更新了@Stichoza的答案,通过子文件夹删除文件。
function glob_recursive($pattern, $flags = 0) {
$fileList = glob($pattern, $flags);
foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
$subPattern = $dir.'/'.basename($pattern);
$subFileList = glob_recursive($subPattern, $flags);
$fileList = array_merge($fileList, $subFileList);
}
return $fileList;
}
function glob_recursive_unlink($pattern, $flags = 0) {
array_map('unlink', glob_recursive($pattern, $flags));
}
这是一个简单的方法和很好的解决方案。试试这段代码。
array_map('unlink', array_filter((array) array_merge(glob("folder_name/*"))));
假设你有一个有很多文件的文件夹,读取它们,然后在两步删除不是执行。 我相信删除文件最有效的方法就是使用系统命令。
例如,在linux上我使用:
exec('rm -f '. $absolutePathToFolder .'*');
如果你想要递归删除而不需要写递归函数
exec('rm -f -r '. $absolutePathToFolder .'*');
PHP支持的任何操作系统都可以使用相同的命令。 请记住,这是一种删除文件的执行方式。$absolutePathToFolder必须检查和安全运行此代码和权限必须被授予。