Tom Tom - 6 months ago 34
PHP Question

Display latest image in directory ending in

I'd like to display the last modified image in a directory that ends in a specific way.

I have it working to display the last file in the directory I only don't know how to go about filtering the result to only display the latest in the directory ending in "wide-block.jpg"

<?php
$base_url = 'images/folio/web-portfolio';
$newest_mtime = 0;
$show_file = 'images/folio/no-image.jpg';
if ($handle = opendir($base_url)) {
while (false !== ($latestFile = readdir($handle))) {
if (($latestFile != '.') && ($latestFile != '..') && ($latestFile != '.htaccess')) {
$mtime = filemtime("$base_url/$latestFile");
if ($mtime > $newest_mtime) {
$newest_mtime = $mtime;
$show_file = "$base_url/$latestFile";
}
}
}
}
echo '<img src="' .$show_file. '" alt="Latest from the web">';
?>


I got that code from somewhere else and realize it won't need the second if statement of != file types listed once my check of display the latest file ending in "wide-block.jpg".

Answer

This should sort it out for you, basically just add another rule to filter in images ending in your required field.

Basically just use the strpos() function to determine if the value you are looking for is in the file name.

Also wrapped the code within a function, allowing bot the desired folder location, and desired string which the file must end in.

<?php
function getLatestImage($folderName, $imageEnding) {
    $newest_mtime = 0;
    $base_url = 'images/folio/'.$folderName;        
    $file_ending = $imageEnding;
    $show_file = 'images/folio/no-image.jpg';
    if ($handle = opendir($base_url)) {
        while (false !== ($latestFile = readdir($handle))) {
            if (($latestFile != '.') && ($latestFile != '..') && ($latestFile != '.htaccess') && (strpos($latestFile, $file_ending))) {
             $mtime = filemtime("$base_url/$latestFile");
                if ($mtime > $newest_mtime) {
                    $newest_mtime = $mtime;
                    $show_file = "$base_url/$latestFile";
                }
            }
        }
    }
    return $show_file;
}

echo '<img src="' .getLatestImage('foldername', 'file_ending.jpg'). '" alt="Latest from the web">';
?>