【问题标题】:How to delete the old files from a directory if a condition is true in PHP?如果 PHP 中的条件为真,如何从目录中删除旧文件?
【发布时间】:2020-02-07 01:06:30
【问题描述】:

我只想在一个文件夹中保留 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);   
}

【问题讨论】:

  • 将所有文件推入一个数组(名称和时间),排序和删除你需要的。
  • 好吧,$files 已经是一个数组了。为什么不使用它而不是使用opendir

标签: php delete-file


【解决方案1】:

为您提供想法的基本脚本。将所有文件及其时间推入一个数组,按时间降序排序并遍历。 if($count &gt; 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++;
    }

【讨论】:

    【解决方案2】:

    您可以简单地将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);
    }
    

    注意:出于本答案的目的,这显然被过度评论了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-22
      • 1970-01-01
      • 1970-01-01
      • 2011-10-02
      • 1970-01-01
      • 2012-05-14
      • 2012-04-23
      • 2018-03-19
      相关资源
      最近更新 更多