简体   繁体   English

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

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

I want to keep only 10 newest files in a folder and delete others.我只想在一个文件夹中保留 10 个最新文件并删除其他文件。 I created a script that deletes only the oldest ones if a file number is larger than 10. How can I adapt this script to my needs?我创建了一个脚本,如果文件号大于 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);   
}

Basic script to give you the idea.基本脚本给你的想法。 Push all the files with their times into an array, sort it by descending time order and walk trough.将所有文件及其时间推入一个数组,按时间降序排序并遍历。 if($count > 10) says when the deletion should start, ie currently it keeps the newest 10. 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++;
    }

You could simply sort the result of scandir by the returned files' modification dates:您可以简单地按返回文件的修改日期对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);
}

Usage:用法:

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

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

Note: this is obviously over-commented for the purpose of this answer.注意:对于这个答案,这显然被过度评论了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM