删除文件夹中的所有文件,但最后一次删除?

时间:2012-02-05 15:37:19

标签: php

之前我问过同样的问题,我找到了这个解决方案:

if ($handle = opendir('/path/to/your/folder')) 
{
$files = array();
while (false !== ($file = readdir($handle))) 
{
    if (!is_dir($file))
    {
        // You'll want to check the return value here rather than just blindly adding to the array
        $files[$file] = filemtime($file);
    }
}

// Now sort by timestamp (just an integer) from oldest to newest
asort($files, SORT_NUMERIC);

// Loop over all but the 5 newest files and delete them
// Only need the array keys (filenames) since we don't care about timestamps now as the array will be in order
$files = array_keys($files);
for ($i = 0; $i < (count($files) - 5); $i++)
{
    // You'll probably want to check the return value of this too
    unlink($files[$i]);
}
}

我已编辑以满足我的需求:

public function cleanup() {
    $files = glob("$this->location/*.sql");
    $count = count($files);
    if($count >= $this->maxbackups) {
        $timestamps = array();
        foreach( $files as $value) {
            $timestamps[$value] = filemtime($value);
        }
        asort($timestamps, SORT_NUMERIC);
        $timestamps = array_keys($timestamps);
        for ($i = 0; $i < (count($timestamps) - 1); $i++) {
            unlink($timestamps[$i]);
        }
            return $this->message->error(false,'Backups successfuly cleaned');
        } else {
            return $this->message->error(true,'Backups could not be cleaned');
        }
}

但问题是它删除了所有文件,但是第一个,而不是最后创建的,为什么呢?

3 个答案:

答案 0 :(得分:3)

使用for ($i = 1; $i < (count($timestamps)); $i++)。这可以使它发挥作用。

答案 1 :(得分:2)

我认为你可以使它更有效并降低复杂性。 (只需要一个循环,而不是两个循环,不需要排序)

$files = glob("$this->location/*.sql");
if( count( $files) < 2){
  return 0; // No files deleted
}

$file = array_shift( $files);
$mTime = filemtime( $file);

foreach( $files as $currFile){
  $currTime = filemtime( $currFile);
  if( $currTime > $mTime){
    unlink( $file);
    $file = $currFile;
    $mTime = $currTime;
  } else {
    unlink( $currFile);
  }
}

答案 2 :(得分:2)

您使用glob进行简化是正确的,但不是手动计数或其他,请尝试:

$files = glob("dir/*.sql");
$files = array_combine($files, array_map("filemtime", $files));

arsort($files); // orders by mtime, newest files first
$files = array_keys($files);
$files = array_slice($files, 5);   // removes the first 5

array_map("unlink", $files);     // delete remaining list

但您当然可以使用手册foreach代替array_map