views:

30

answers:

2

I have a directory that will be getting updated frequently, I want to display the last four images files uploaded, which match a certain pattern, on my php page.

Is this possible without having to perform a sort on every single image within the directory?

Many thanks!

A: 

Dunno what do you call "to perform a sort on every single image within the directory", but you have to read all file names into array and then read ctime for the every file. and then sort the resulting array.

Col. Shrapnel
A: 

You'll always have to sort if you want the last four files, but you might as well let the filesystem do it for you. This will work on linux unless your pattern's a regex:

$pattern = '*.jpg';
exec( "ls $pattern -1t | head -4", $files );
foreach( $files as $thisFile ) {
    echo "<img src='", $serverPathToFiles, $thisFile, "' alt='blah' />\n";
}

If you have to use a regex, change the first two lines to

$pattern = 'web2\.[4-5]'; // for web2.42 etc.
exec( "ls -1t | grep -e $pattern | head -4", $files );
Andy
Hi Andy, thanks for the reply. Although I'm not accepting any user input for the filenames, or any other part of this code, I was wondering whether you knew of any security or performance issues I might face when executing system commands like this?
purpletonic
@purpletonic Security: apache will require permissions to access filesystem folder; never pass unescaped user input to shell. Performance: none, unless directory is very large; after the first read the filesystem will cache the file handles and subsequent reads will be faster; regex is always slightly slower.
Andy
@Andy : Thanks for the pointers. As I mentioned there's no user submitted input, so it should be OK with that. Just wanted to check for other security issues, and performance. Had to use Regex with egrep but your solution was easily modified. Cheers!
purpletonic