例如,我有一个名为“Temp”的文件夹,我想使用PHP删除或刷新该文件夹中的所有文件。我可以这样做吗?
当前回答
<?
//delete all files from folder & sub folders
function listFolderFiles($dir)
{
$ffs = scandir($dir);
echo '<ol>';
foreach ($ffs as $ff) {
if ($ff != '.' && $ff != '..') {
if (file_exists("$dir/$ff")) {
unlink("$dir/$ff");
}
echo '<li>' . $ff;
if (is_dir($dir . '/' . $ff)) {
listFolderFiles($dir . '/' . $ff);
}
echo '</li>';
}
}
echo '</ol>';
}
$arr = array(
"folder1",
"folder2"
);
for ($x = 0; $x < count($arr); $x++) {
$mm = $arr[$x];
listFolderFiles($mm);
}
//end
?>
其他回答
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目录下的所有文件。
$dir = 'your/directory/';
foreach(glob($dir.'*.*') as $v){
unlink($v);
}
foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
if(!$fileInfo->isDot()) {
unlink($fileInfo->getPathname());
}
}
以下代码来自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);
}
}
如果你想删除文件夹中的所有内容(包括子文件夹),请使用array_map, unlink和glob的组合:
array_map( 'unlink', array_filter((array) glob("path/to/temp/*") ) );
这个调用还可以处理空目录(感谢您的提示,@mojuba!)