如果 PHP 中的条件为真,如何从目录中删除旧文件?

How to delete the old files from a directory if a condition is true in PHP?

我想在一个文件夹中只保留 10 个最新文件并删除其他文件。 我创建了一个脚本,如果文件编号大于 10,则只删除最旧的文件。 我怎样才能使这个脚本适应我的需要?

$directory = "/home/dir";

// Returns array of files
$files = scandir($directory);

// Count number of files and store them to variable..
$num_files = count($files)-2;
if($num_files>10){

    $smallest_time=INF;

    $oldest_file='';

    if ($handle = opendir($directory)) {

        while (false !== ($file = readdir($handle))) {

            $time=filemtime($directory.'/'.$file);

            if (is_file($directory.'/'.$file)) {

                if ($time < $smallest_time) {
                    $oldest_file = $file;
                    $smallest_time = $time;
                }
            }
        }
        closedir($handle);
    }  

    echo $oldest_file;
    unlink($oldest_file);   
}

给你想法的基本脚本。将所有文件及其时间推送到一个数组中,按时间降序排序并遍历。 if($count > 10) 表示何时开始删除,即目前它保留最新的 10。

<?php
    $directory = ".";

    $files = array();
    foreach(scandir($directory) as $file){
        if(is_file($file)) {

            //get all the files
            $files[$file] = filemtime($file);
        }
    }

    //sort descending by filemtime;
    arsort($files);
    $count = 1;
    foreach ($files as $file => $time){
        if($count > 10){
            unlink($file);
        }
        $count++;
    }

您可以简单地按返回文件的修改日期对 scandir 的结果进行排序:

/**
 * @return string[]
 */
function getOldestFiles(string $folderPath, int $count): array
{
  // Grab all the filenames
  $filenames = @scandir($folderPath);
  if ($filenames === false) {
    throw new InvalidArgumentException("{$folderPath} is not a valid folder.");
  }

  // Ignore folders (remove from array)
  $filenames = array_filter($filenames, static function (string $filename) use ($folderPath) {
    return is_file($folderPath . DIRECTORY_SEPARATOR . $filename);
  });

  // Sort by ascending last modification date (older first)
  usort($filenames, static function (string $file1Name, string $file2Name) use ($folderPath) {
    return filemtime($folderPath . DIRECTORY_SEPARATOR . $file1Name) <=> filemtime($folderPath . DIRECTORY_SEPARATOR . $file2Name);
  });

  // Return the first $count
  return array_slice($filenames, 0, $count);
}

用法:

$folder = '/some/folder';
$oldestFiles = getOldestFiles($folder, 10);

foreach ($oldestFiles as $file) {
  unlink($folder . '/' . $file);
}

注意:为了这个答案的目的,这显然被过度评论了。