Warm tip: This article is reproduced from stackoverflow.com, please click
php delete-file

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

发布于 2020-03-29 21:02:13

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);   
}
Questioner
user12775148
Viewed
20
mitkosoft 2020-01-31 19:06

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