删除所有文件但保留最新文件

时间:2016-11-23 07:52:33

标签: php delete-file

我在目录中有几个(存档的)备份文件;文件名以“backup - ”开头。

我想删除所有早于7天的文件,但是应该总是留下一个文件(最新的),否则我就没有备份文件了。

我有源代码(见下文),它将删除超过7天的所有文件,但如何始终将最新文件保留在目录中?所以,剩下的一个可以超过7天(如果这是最新的)。

$bu_days=7;
$files="backup*.tar.gz";

foreach(glob($filter) as $fd) {
  if(is_file($fd) && time() - filemtime($fd) >= $bu_days*24*60*60) {unlink($fd);}
}

3 个答案:

答案 0 :(得分:1)

您可以按日期对文件进行排序,然后删除除第一个之外的所有文件:

$bu_days=7;
$files="backup*.tar.gz";

//retrieve all files
$theFiles = glob($files);

//combine the date as a key for each file
$theFiles = array_combine(array_map("filemtime", $theFiles), $theFiles);

//sort them, descending order
krsort($theFiles);

//remove the first item
unset($theFiles[0]);

foreach($theFiles as $fd){
    if(is_file($fd) && time() - filemtime($fd) >= $bu_days*24*60*60) {unlink($fd);}
}

答案 1 :(得分:0)

更新来源:

//declare after how many days files are too old
$bu_days=7;

//declare how many files always should be kept                              
bu_min=3;

//define file pattern
$files="backup*.tar.gz";

//retrieve all files
$theFiles = glob($files);

//combine the date as a key for each file
$theFiles = array_combine($theFiles, array_map("filemtime", $theFiles));

//sort array, descending order (newest first)
arsort($theFiles);

//return subset of the array keys
$f = array_keys($theFiles);

// keep the first $bu_min files of the array, by deleting them from the array
$f = array_slice($theFiles, $bu_min);

// delete every file in the array which is >= $bu_days days
foreach($theFiles as $fd){
  if(is_file($fd) && time() - filemtime($fd) >= $bu_days*24*60*60) {unlink($fd);}
}

答案 2 :(得分:0)

$f = array_keys($theFiles);
$f = array_slice($theFiles, $bu_min);

$f应该是$theFiles