【问题标题】:Delete all files but keep the newest one(s)删除所有文件但保留最新文件
【发布时间】:2019-02-23 22:51:10
【问题描述】:

我在一个目录中有几个(存档的)备份文件;以“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);}
}

【问题讨论】:

  • 数数你的文件然后破解;只剩下 1 个文件时的 foreach ?
  • 您必须在删除任何内容之前进行一些测试。

标签: php delete-file


【解决方案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);}
}

【讨论】:

  • 谢谢 Veve,我认为您的源代码中有一个小错误:您忘记了“foreach(theFiles as $fd){”中的 $(在 theFiles 之前)。
  • 您可以使用“unset(array[0])”代替“first=true”等,这会将其从数组中删除
  • @ni_hao 你说得对,我已经用你的提示和一个更好的解决方案编辑了我的答案,它不需要为每个文件多次访问文件日期。
  • 再次感谢。同时,我希望更加灵活,不仅保留第一个文件,而且定义始终应保留多少个文件。我还更改了(修饰)你的“array_combine”行,我更喜欢使用数组,这让我找到了更新的来源
  • 感谢您的帮助。上面发布的更新源(2 个答案)
【解决方案2】:

更新来源:

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

【讨论】:

    【解决方案3】:
    $f = array_keys($theFiles);
    $f = array_slice($theFiles, $bu_min);
    

    $f 应该是$theFiles

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-23
      • 2020-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      相关资源
      最近更新 更多