Jump to content

Display newest image in directory


walkblind

Recommended Posts

I'm trying to work on a script that simply displays the newest image in a given "images" directory.  I want it to be an include file so that when I place it in the body, the newest image is displayed.  It would be nice if there was a NAVbar updating so that the images leading up to the newest update could also be viewed.  Any pointers would be MUCH appreciated as it will probably shave a day off my efforts.  Thank you !!

Link to comment
https://forums.phpfreaks.com/topic/171490-display-newest-image-in-directory/
Share on other sites

$directoryPath = 'path/to/directory';
$files = scandir($directoryPath);
$newest = 0;
$newestImage = '';
foreach ($files as $file) {
    if ('.' === $file[0] || !preg_match_all('/\.(jpe?g|png|gif)$/', $file)) continue;
    $fullPath = implode(DIRECTORY_SEPARATOR, array($directoryPath, $file));
    if (($ctime = filectime($fullPath)) > $newest) {
        $newest = $ctime;
        $newestImage = $fullPath;
    }
}

 

This gives you the time the $newest image was entered and the full path to the image in $newestImage.

thanks for quick response.  I've plugged in your solution but I get the following warning:

 

Warning: preg_match_all() expects at least 3 parameters, 2 given in .../public_html/php/includes/newest.php on line 7

 

(newest.php being the name of the file i created with your code, of course)

$directoryPath = 'path/to/directory';
$files = scandir($directoryPath);
$newest = 0;
$newestImage = '';
foreach ($files as $file) {
    if ('.' === $file[0] || !preg_match('/\.(jpe?g|png|gif)$/', $file)) continue;
    $fullPath = implode(DIRECTORY_SEPARATOR, array($directoryPath, $file));
    if (($ctime = filectime($fullPath)) > $newest) {
        $newest = $ctime;
        $newestImage = $fullPath;
    }
}

 

This gives you the time the $newest image was entered and the full path to the image in $newestImage.

 

Fixed it.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.