-1

I am trying to display the most recent images added to a portfolio items folder to use as featured images - The code below is doing a good job of getting an image from the specified folder, however it's not displaying the last one to be uploaded… any suggestions?

<?php
$files= glob('./uploads/test/'. $user->id .'/'.$item->id.'/*');
$count = 0;
$user_avatar = '/images/noimage.jpg'; 
if (!file_exists('./uploads/test/'. $user->id .'/'.$item->id.'/*')) { 
  $user_avatar = '/images/noimage.jpg';
} 

 // otherwise continue
foreach ($files as $file) {
$count++;
if ($count > 0 && is_file($file)) { 
$user_avatar = $file;
} 
}
?> 
  • Look at the docs for `filemtime()` - http://php.net/manual/en/function.filemtime.php – WillardSolutions Oct 10 '17 at 14:04
  • Unless you have an actual file called `*` (which I doubt), this `file_exists('./uploads/test/'. $user->id .'/'.$item->id.'/*')` will _always_ return false. You can't have a wild card in that function call. – M. Eriksson Oct 10 '17 at 14:10

1 Answers1

0

Please use filemtime to compare files timestamp. You can do like this to get latests :

$files = glob("*.*.html");
usort($files, function($a,$b){
  return filemtime($a) - filemtime($b);
});
Medhi
  • 2,656
  • 23
  • 16
  • Please flag to close questions that are suitably answered else where in the community. @Magnus nominated the page that I just hammered this page with (his link was automatically removed when I closed the page). This means, if you would have followed his link, you would have found your suggestion was already there. The system has a harder time removing redundant pages when an answer is posted. – mickmackusa Apr 16 '20 at 14:12