Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get latest file from directory including subdirectories

I want to get the latest file from a directory, including the subdirectories in it.

I have these folders:

MainFolder
├───Folder1
│       File135646.txt
│       File341324.txt
│
└───Folder2
        File467456.txt
        File745674.txt

I want it to return an array like this, showing the latest to oldest files:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Array ( [0] => Folder1/File135646.txt [1] => Folder2/File467456.txt [2] => Folder2/File745674.txt [3] => Folder1/File341324.txt )

Each element would contain folder/file but the order would be from latest to oldest file. I have tried this, but it doesn’t work with subdirectories.

scandir('folder', SCANDIR_SORT_ASCENDING)

>Solution :

I have updated this function (List all the files and folders in a Directory with PHP recursive function) to include modification time. Then sorted by it.


function getDirContents($dir, &$results = array()) {
    $files = scandir($dir);

    foreach ($files as $key => $value) {
        $path = realpath($dir . DIRECTORY_SEPARATOR . $value);
        if (!is_dir($path)) {
            $results[] = [
                "path" => $path,
                "mtime" => filemtime($path)
            ];
        } else if ($value != "." && $value != "..") {
            getDirContents($path, $results);
            $results[] = [
                "path" => $path,
                "mtime" => filemtime($path)
            ];
        }
    }

    usort($results, function($a, $b) {
        return $a["mtime"] <=>$b["mtime"];
    });
    return $results;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading