Search code examples
phpsqldatabasebackupdatabase-backups

List files from directory with .zip extension and sort by newest created file first


I thought i would share something useful, so i wanted to list only .zip files in a directory (to minimise what i am displaying in PHP for security) so i have used the below script with the newest files on top.

This is just some code i wanted to share incase anyone else needed to do something similar.

<?php

function list_zipfiles($mydirectory, 1) {

    // directory we want to scan
    $dircontents = scandir($mydirectory);

    // list the contents
    echo '<ul>';
    foreach ($dircontents as $file) {
        $extension = pathinfo($file, PATHINFO_EXTENSION);
        if ($extension == 'zip') {
            echo "<li>$file </li>";
        }
    }
    echo '</ul>';
}
?>
<h6 class="header1">PRODUCTION</h6>
<hr class="style1">
<?php
call_user_func('list_zipfiles', "backups/db1");
?>

The 1 below sets the listing order of the files, changing it to 0 orders it in the other direction:

function list_zipfiles($mydirectory, 1) {

The output is as below:

enter image description here


Solution

  • Please see my above answer as to how i have listed all .zip files in a given directory, order it by filename and used as a function so i can easily repeat the use elsewhere.