0

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);   
}
2
  • 1
    Push all the files into an array (name and time), sort and delete what you need.
    – mitkosoft
    Jan 31, 2020 at 10:52
  • Well, $files is already an array. Why not use it instead of using opendir?
    – Jeto
    Jan 31, 2020 at 10:54

2 Answers 2

0

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++;
    }
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.