Getting the most recent file.
Posted: Sat Jun 03, 2006 5:01 pm
I writing a system that generates a file whenever it's run. Each time it runs it creates a new file. Not a problem. However, I'm also writing something that needs to go and get the last file and open it. Ideally I'd like to do this using the file creation date.. it's recorded so it makes sense to use it. Coding something to do that is pretty trivial:
However .. that isn't exactly scalable. When my system starts having many thousands of files it'll grind to a halt. Is there any method to order the results of glob() so I can just use the first result? Is there a suitable alternative to glob()? I know I could name the files in order and use the filename which would eliminate the call to stat(), but I'd rather not do that as files might eventually come from sources other than those I control.
Code: Select all
function getLatestFile() {
$files = glob("file/*.prs");
$ptime = 0;
foreach ($files as $f) {
$a = stat($f);
if ($a['ctime'] > $ptime) {
$ptime = $a['ctime'];
$latestfile = $f;
}
}
return $latestfile;
}