2

I'm looking for a script to loop through a folder and delete all the files inside it but the last, most recent one ( I have marked the name of each file as filename_date('Y')_date('m')_date('d').extension), not sure if relevant ).

I have found this script here on stack:

if ($handle = opendir('/path/to/your/folder')) 
{
    $files = array();
    while (false !== ($file = readdir($handle))) 
    {
        if (!is_dir($file))
        {
            // You'll want to check the return value here rather than just blindly adding to the array
            $files[$file] = filemtime($file);
        }
    }

    // Now sort by timestamp (just an integer) from oldest to newest
    asort($files, SORT_NUMERIC);

    // Loop over all but the 5 newest files and delete them
    // Only need the array keys (filenames) since we don't care about timestamps now as the array will be in order
    $files = array_keys($files);
    for ($i = 0; $i < (count($files) - 5); $i++)
    {
        // You'll probably want to check the return value of this too
        unlink($files[$i]);
    }
}

This above deletes anything but the last five. Is this a good way to do it ? Or is there another way, simpler or better one ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Roland
  • 9,321
  • 17
  • 79
  • 135

3 Answers3

2

That works. I don't believe there's a simpler way to do it. Plus, your solution is actually quite simple.

Simon Germain
  • 6,834
  • 1
  • 27
  • 42
1

i think is a good solution. just modify the loop

but you could avoid for loop sorting array in descend mode so you could delete all the rest of array saving just the first file EDIT sort from newest to older

Jayyrus
  • 12,961
  • 41
  • 132
  • 214
0

i know this is old but you could also do it like this

$directory = array_diff(scandir(pathere), array('..', '.'));
$files = [];
foreach ($directory as $key => $file) {
    $file = pathere.$file;
    if (file_exists($file)) {
        $name = end(explode('/', $file));
        $timestamp = preg_replace('/[^0-9]/', '', $name);
        $files[$timestamp] = $file;
    }
}
// unset last file
unset( $files[max(array_keys($files))] );
// delete old files
foreach ($files as $key => $dfiles) {
    if (file_exists($dfiles)) {
        unlink($dfiles);
    }
}
Zoric
  • 61
  • 12