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

家住魔仙堡 提交于 2021-02-11 13:32:30

问题


I want to keep only 10 newest files in a folder and delete others. 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?

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

回答1:


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, i.e. currently it keeps the newest 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:


You could simply sort the result of scandir by the returned files' modification dates:

/**
 * @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.



来源:https://stackoverflow.com/questions/60002347/how-to-delete-the-old-files-from-a-directory-if-a-condition-is-true-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!