PHP: Select the latest image or file in a folder
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!