首页 > 解决方案 > 我已经看到使用 php 在文件夹中显示第一张图像的代码,即最新图像,现在我如何使代码显示第二张和第三张

问题描述

我希望此代码显示文件夹中的第二张图像。你可以给我看另一个可以显示第三张图片的代码,谢谢。请,您的代码将不胜感激。

like so

<?php
$dir = 'uploads/';
$base_url = 'http://localhost/zac/uploads/';
$newest_mtime = 0;
$show_file = 'BROKEN';
if ($handle = opendir($dir)) {
 while (false !== ($file = readdir($handle))) {
    if (($file != '.') && ($file != '..')) {
       $mtime = filemtime("$dir/$file");
       if ($mtime > $newest_mtime) {
          $newest_mtime = $mtime;
          $show_file = "$base_url/$file";
       }
    }
  }
}
print '<img src="' .$show_file. '" alt="Image Title Here">';
?>

标签: phpimagedirectorysubdirectorydisplay

解决方案


这是从 localhost 获取目录文件的另一种方法。

$base_url = 'http://localhost/zac/uploads/';
$dir = 'uploads/';
$files = glob($dir."*.*");
usort( $files, function( $a, $b ) { return filemtime($b) - filemtime($a); } );
$i = 1;
foreach($files as $file) {
$remove_ext = substr($file, 0, strrpos($file, "."));
  if($i <= 3){
    echo '<img src="'.$base_url.$file.'" alt="'.$remove_ext.'" ></br>';
  }
 $i++;
}

推荐阅读