Search code examples
phpsortingdownload

php - sort based on date and download link for latest 5 files


I have the below code, which gives a download link for all files with a .sh extension. I am trying to modify it to give the link only for latest 5 files, and it's not working.

if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle)))
    {
        if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'sh')
        {
            echo '<a href="'.$file.'">'.$file.'</a>'."<br>";
        }
    }
    closedir($handle);
}

Solution

  • array_multisort(
        array_map(
            'filemtime',
            ($files = glob("*.sh*"))
        ),
        SORT_DESC,
        $files
    );
    $newest = array_slice($files, 0, 5);
    foreach ($newest as $value) {
        echo '<a href="' . $value . '">' . $value . '</a>' . "<br>";
    }