php根据目录图片文件名显示最新图片

img目录 目前有3张图片 637 638 639 下周会增加640我想实现这样的效果 输入下面网址时http://127.0.0.5/index.php?id=637 网页里则显示 <title>637</title><img src="./img/637.jpg>http://127.0.0.5/index.php?id=638网页里则显示 <title>638</title> <img src="./img/638.jpg>http://127.0.0.5/index.php?id=639网页里则显示 <title>639</title><img src="./img/639.jpg>当直接输入http://127.0.0.5/时 显示img目录数字最大的那张图片639比如以后我往目录上传了一张640 输入http://127.0.0.5/时自动显示640然后底部所有图片网页链接都能显示出来
2026年09月22日 14:22
有1个网友回答
网友(1):

可以根据文件的创建时间来做。

$dh = opendir('images');
$newest_file = null;
$time = null;
while ($file = readdir($dh)) {
    $filename = 'images' . '/' . $file;
    if ($time === null || filectime($filename) > $time) {
        $newest_file = $filename;
        $time = filectime($filename);
    }
}
if ($newest_file)
    echo sprintf('', $newest_file);