I am looking for code which lists the five most recent files in a directory recursively.
This is non-recursive code, and would be perfect for me if it was recursive:
This was my first version (tested, working):
function latest($searchDir, array $files = array()) {
$search = opendir($searchDir);
$dirs = array();
while($item = readdir($search)) {
if ($item == '.' || $item == '..') { continue; }
if (is_dir($searchDir.'/'.$item)) {
$dirs[] = $searchDir.'/'.$item;
}
if (is_file($searchDir.'/'.$item)) {
$ftime = filemtime($searchDir.'/'.$item);
$files[$ftime] = $searchDir.'/'.$item;
}
}
closedir($search);
if (count($dirs) > 0) {
foreach ($dirs as $dir) {
$files += latest($dir,$files);
}
}
krsort($files);
$files = array_slice($files, 0, 5, true);
return $files;
}
But I like byte's usage of glob()
, so here is a slightly modified version of his to return the same format:
function top5modsEx($dir) {
$mods = array();
foreach (glob($dir . '/*') as $f) {
$mods[filemtime($f)] = $f;
}
krsort($mods);
return array_slice($mods, 0, 5, true);
}
This returns the time (UNIX Timestamp format) that the file was modified as the key of the element in the array.