例如,我有一个名为“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);
    }
}

其他回答

foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
    if(!$fileInfo->isDot()) {
        unlink($fileInfo->getPathname());
    }
}

假设你有一个有很多文件的文件夹,读取它们,然后在两步删除不是执行。 我相信删除文件最有效的方法就是使用系统命令。

例如,在linux上我使用:

exec('rm -f '. $absolutePathToFolder .'*');

如果你想要递归删除而不需要写递归函数

exec('rm -f -r '. $absolutePathToFolder .'*');

PHP支持的任何操作系统都可以使用相同的命令。 请记住,这是一种删除文件的执行方式。$absolutePathToFolder必须检查和安全运行此代码和权限必须被授予。

如果你想删除文件夹中的所有内容(包括子文件夹),请使用array_map, unlink和glob的组合:

array_map( 'unlink', array_filter((array) glob("path/to/temp/*") ) );

这个调用还可以处理空目录(感谢您的提示,@mojuba!)

以下代码来自http://php.net/unlink:

/**
 * Delete a file or recursively delete a directory
 *
 * @param string $str Path to file or directory
 */
function recursiveDelete($str) {
    if (is_file($str)) {
        return @unlink($str);
    }
    elseif (is_dir($str)) {
        $scan = glob(rtrim($str,'/').'/*');
        foreach($scan as $index=>$path) {
            recursiveDelete($path);
        }
        return @rmdir($str);
    }
}
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);
}