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


当前回答

另一个解决方案: 该类删除所有文件、子目录和子目录中的文件。

class Your_Class_Name {
    /**
     * @see http://php.net/manual/de/function.array-map.php
     * @see http://www.php.net/manual/en/function.rmdir.php 
     * @see http://www.php.net/manual/en/function.glob.php
     * @see http://php.net/manual/de/function.unlink.php
     * @param string $path
     */
    public function delete($path) {
        if (is_dir($path)) {
            array_map(function($value) {
                $this->delete($value);
                rmdir($value);
            },glob($path . '/*', GLOB_ONLYDIR));
            array_map('unlink', glob($path."/*"));
        }
    }
}

其他回答

发布了一个通用的文件和文件夹处理类,用于复制,移动,删除,计算大小等,可以处理单个文件或一组文件夹。

https://gist.github.com/4689551

使用方法:

复制(或移动)一个文件或一组文件夹/文件:

$files = new Files();
$results = $files->copyOrMove('source/folder/optional-file', 'target/path', 'target-file-name-for-single-file.only', 'copy');

删除单个文件或删除路径下的所有文件和文件夹:

$files = new Files();
$results = $files->delete('source/folder/optional-file.name');

计算单个文件或一组文件夹中文件的大小:

$files = new Files();
$results = $files->calculateSize('source/folder/optional-file.name');
$dir = 'your/directory/';
foreach(glob($dir.'*.*') as $v){
    unlink($v);
}

Unlinkr函数递归删除给定路径下的所有文件夹和文件,确保它不删除脚本本身。

function unlinkr($dir, $pattern = "*") {
    // find all files and folders matching pattern
    $files = glob($dir . "/$pattern"); 

    //interate thorugh the files and folders
    foreach($files as $file){ 
    //if it is a directory then re-call unlinkr function to delete files inside this directory     
        if (is_dir($file) and !in_array($file, array('..', '.')))  {
            echo "<p>opening directory $file </p>";
            unlinkr($file, $pattern);
            //remove the directory itself
            echo "<p> deleting directory $file </p>";
            rmdir($file);
        } else if(is_file($file) and ($file != __FILE__)) {
            // make sure you don't delete the current script
            echo "<p>deleting file $file </p>";
            unlink($file); 
        }
    }
}

如果你想删除你放置这个脚本的所有文件和文件夹,然后像下面这样调用它

//get current working directory
$dir = getcwd();
unlinkr($dir);

如果你只想删除PHP文件,那么就像下面这样调用它

unlinkr($dir, "*.php");

您也可以使用任何其他路径删除文件

unlinkr("/home/user/temp");

这将删除home/user/temp目录下的所有文件。

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

array_map('unlink', array_filter((array) array_merge(glob("folder_name/*"))));
foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
    if(!$fileInfo->isDot()) {
        unlink($fileInfo->getPathname());
    }
}