Я ищу сценарий, чтобы перебирать папку и удалять все файлы внутри нее, но последние, самые последние (я отметил имя каждого файла как filename_date('Y')_date('m')_date('d').extension)
, не уверен, если это необходимо).Удалить все файлы внутри папки, но последние?
Я нашел этот сценарий здесь на стеке:
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]);
}
}
Это выше удаляет все, кроме последних пяти. Это хороший способ сделать это? Или есть другой способ, более простой или лучший?