Wednesday, September 2, 2009

PHP Get Oldest File

I was looking around to make sure there wasn't some sort of built-in function in PHP now for determining the oldest file in a directory. I didn't find a built-in function that returns the oldest file, but I found plenty of user functions that were not what I was looking for.

So, I wrote my own old file getter function. The function will accept either an array of file paths or a string which will be passed to glob in order to get an array of file paths. The function returns the oldest file found.

function oldest_file($dir)
{
if(is_string($dir))
{
$dir = glob($dir);
}
$oldest = array_shift($dir);
foreach($dir as $file)
{
if(filemtime($file) < filemtime($oldest))
{
$oldest = $file;
}
}
return $oldest;
}

2 comments:

Anonymous said...

You have scientology ads on your blog.

Joe Kovar said...

The ads are "User Targeted" so if you see ads about that it means Google thinks it's something you would be interested in based on what you've been reading and searching for...

I see ads for technology companies. :)