Skip to content
Advertisement

I have seen the code that displays the first image i.e latest image in a folder using php, now how do i make the code to display the second and third

I want this code to display the second image from a folder. You can show me another code that can display the third image, Thank You. Please, your codes would be appreciated.

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">';
?>

Advertisement

Answer

Here is another way to grab directory files from 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++;
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement