Delete all files inside a folder but the last?

主宰稳场 提交于 2019-12-24 02:40:15

问题


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 ?


回答1:


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




回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/9113145/delete-all-files-inside-a-folder-but-the-last

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!