Page 1 of 1

Getting the most recent file.

Posted: Sat Jun 03, 2006 5:01 pm
by onion2k
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:

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;
}
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.

Posted: Sat Jun 03, 2006 5:40 pm
by Christopher
You might be better off just capturing the output of "ls -t"

Posted: Sat Jun 03, 2006 6:08 pm
by n00b Saibot
or you might try storing the name of the latest file generated somewhere so that it's just the matter of reading file name from that location. pretty simple...

Posted: Sun Jun 04, 2006 8:23 am
by onion2k
Can't capture "ls -t" as the code need to be cross-platform and work in safe mode.

Can't really store the name of the file because people will be uploading them .. I need to be *certain* it's the latest file even if someone has uploaded incorrectly (eg via FTP instead of a web interface).

Posted: Sun Jun 04, 2006 8:37 am
by Chris Corbyn
I'd probably look at recording the latest file name in a DB and just pulling that one. Seems reasonable.

Posted: Sun Jun 04, 2006 10:41 am
by onion2k
d11wtq wrote:I'd probably look at recording the latest file name in a DB and just pulling that one. Seems reasonable.
People might upload a file via FTP.. The latest file might never have been seen by a script.