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:
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)
CodePudding user response:
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;
}