例如,我有一个名为“Temp”的文件夹,我想使用PHP删除或刷新该文件夹中的所有文件。我可以这样做吗?


当前回答

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);
}
foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
    if(!$fileInfo->isDot()) {
        unlink($fileInfo->getPathname());
    }
}

我已经构建了一个非常简单的包,叫做“Pusheh”。使用它,您可以清除目录或完全删除目录(Github链接)。Packagist上也有。

例如,如果你想清除Temp目录,你可以这样做:

Pusheh::clearDir("Temp");

// Or you can remove the directory completely
Pusheh::removeDirRecursively("Temp");

如果你感兴趣,可以查看维基。

在PHP中删除文件夹中的所有文件的简单和最好的方法

$files = glob('my_folder/*'); //get all file names
foreach($files as $file){
    if(is_file($file))
    unlink($file); //delete file
}

从这里得到这个源代码- http://www.codexworld.com/delete-all-files-from-folder-using-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);
    }
}