PHP删除目录下所有的文件

时间:2017-07-28
本文章向大家介绍PHP如何删除目录下所有的文件(包括隐藏的文件,例如.htaccess),需要的朋友可以参考一下。

我有一个名为`Temp'的文件夹,我想使用PHP删除此文件夹中的所有文件。我可以这样做吗?

实现方法

方法一:使用unlink

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

如果你想删除像'.htaccess这样的'隐藏'文件,你必须使用

$files = glob('path/to/temp/{,.}*', GLOB_BRACE);

方法二:

如果你想删除一切从文件夹(包括子文件夹)使用这个组合array_mapunlink以及glob

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

方法三:

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目录中的所有文件。