Roland Roland - 28 days ago 6
PHP Question

Delete all files inside a folder but the last?

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 ?

Answer Source

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