Startup

Technology Review

Tips

Video

Welcome

Home » Technology Review

PHP: Select the latest image or file in a folder

Submitted by admin on Wednesday, 27 August 2008No Comment

It can be useful to set a placeholder in a web page, such as an image, and for this place holder to be set to be the latest file in a given folder; or to select a random image/file from a given folder and set it as the placeholder. For example in an image of the day or daily quote scenario.

// set this value to 1 for a random image, or zero for the latest image
$userand = 0;
// folder where the images are located
$dir = “targetfolder”;
// filemask to match images
$filemask = “*.{gif}”;
// name of the target image
$oldfile = “placeholderfile.gif”;
//set a random seed using the system time
mt_srand( (double)microtime()*1000000 );
// change to the given directory
if ( $dir )
{
// change to the given directory
chdir( $dir );
// remove the old latest image - if it exists
if ( file_exists ( $dir . “/” . $oldfile ) ) { unlink( $dir . “/” . $oldfile ); }
// $files = glob( ‘*.{html,php,php4,txt}’, GLOB_BRACE );
$files = glob( $filemask, GLOB_BRACE );
// count the number of files returned
$countfiles = count($files);
// only continue if files are found
if ( $countfiles > 0 )
{
// sort the files into date order
usort( $files, ‘compare_filetime’ );
// copy the selected file
if ( $userand == 0 )
{
// copy the file
copy ( $dir . “/” . $files[0] , $dir . “/” . $oldfile );
}
else
{
// select a random file
$randfile = mt_rand (0, $countfiles-1 );
// copy the random file
copy ( $dir . “/” . $files[$randfile] , $dir . “/” . $oldfile );
}
}
}
// compare the dates/times of files and return the latest one
function compare_filetime( $file1, $file2 )
{
return filemtime( $file2 ) - filemtime( $file1 );
}

Leave a comment!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.