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

问题描述 投票:0回答:3

我在目录中有几个(存档的)备份文件;文件名以“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);}
}
php delete-file
3个回答
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);}
}

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);}
}

0
投票
$f = array_keys($theFiles);
$f = array_slice($theFiles, $bu_min);

$f应该是$theFiles

© www.soinside.com 2019 - 2024. All rights reserved.