I have PHP file that generates gallery from a directory of images.
I want to sort images by modification date.
I’m trying to use filemtime function then sort function using the following code:
<?php $src_folder = 'gallery'; $src_files = scandir($src_folder); function filetime_callback($a, $b) { if (filemtime($src_folder.'/'.$a) === filemtime($src_folder.'/'.$b)) return 0; return filemtime($src_folder.'/'.$a) > filemtime($src_folder.'/'.$b) ? -1 : 1; } $files = array(); usort($files, "filetime_callback"); foreach($src_files as $file) { echo $file . ' - ' . date ("F d Y H:i:s.", filemtime($src_folder.'/'.$file)) . '<br>'; } ?>
And the output is like this:
image01.jpg - October 22 2017 19:40:02. image02.jpg - October 22 2017 19:39:19. image03.jpg - October 22 2017 19:39:23. image04.jpg - October 22 2017 19:39:28.
It is not sorted by modification date.
How can I make my code work?
Advertisement
Answer
function scan_dir($dir) { $ignored = array('.', '..', '.svn', '.htaccess'); $files = array(); foreach (scandir($dir) as $file) { if (in_array($file, $ignored)) { continue; } $filemtime = filemtime($dir . '/' . $file); $files[$file] = $filemtime; } arsort($files); $files = array_keys($files); return ($files) ? $files : false; } $src_folder = 'gallery'; $files = scan_dir($src_folder); foreach($files as $file) { echo $file . ' - ' . date ("F d Y H:i:s.", filemtime($src_folder.'/'.$file)) . '<br>'; }