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

 

实现方法

方法一:使用un

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

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

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

 

方法二:

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

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

 

方法三:

un r函数通过确保它不删除脚本本身来递归删除给定路径中的所有文件夹和文件。

function un r($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 un r function to delete files inside this directory     
        if (is_dir($file) and !in_array($file, array(\'..\', \'.\')))  {
            echo \"<p>opening directory $file </p>\";
            un r($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  
            echo \"<p>deleting file $file </p>\";
            un ($file); 
        }
    }
}

如果要删除放置此脚本的所有文件和文件夹,请按以下方式调用它

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

如果你只想删除只是php文件,然后将其称为如下

un r($dir, \"*.php\");

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

un r(\"/home/user/temp\");

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

收藏 打印