Getting the most recent file.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Getting the most recent file.

Post 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.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

You might be better off just capturing the output of "ls -t"
(#10850)
User avatar
n00b Saibot
DevNet Resident
Posts: 1452
Joined: Fri Dec 24, 2004 2:59 am
Location: Lucknow, UP, India
Contact:

Post 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...
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post 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).
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

I'd probably look at recording the latest file name in a DB and just pulling that one. Seems reasonable.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post 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.
Post Reply