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


当前回答

在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/

其他回答

参见readdir和unlink。

<?php
    if ($handle = opendir('/path/to/files'))
    {
        echo "Directory handle: $handle\n";
        echo "Files:\n";

        while (false !== ($file = readdir($handle)))
        {
            if( is_file($file) )
            {
                unlink($file);
            }
        }
        closedir($handle);
    }
?>

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

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

Pusheh::clearDir("Temp");

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

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

以下代码来自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);
    }
}

下面是一种使用标准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);
    }
}

这是一个简单的方法和很好的解决方案。试试这段代码。

array_map('unlink', array_filter((array) array_merge(glob("folder_name/*"))));