How to get X latest files from a directory in PHP?

The code below is part of the function for capturing 5 image files from a given directory.

Readdir currently returns images "in the order in which they are stored by the file system" according to the specification .

My question is, how can I change it to get the last 5 images? Either based on the last_modified date, or the file name (which look like 0000009-16-5-2009.png, 0000012-17-5-2009.png, etc.).

 if ( $handle = opendir($absolute_dir) ) { $i = 0; $image_array = array(); while ( count($image_array) < 5 && ( ($file = readdir($handle)) !== false) ) { if ( $file != "." && $file != ".." && $file != ".svn" && $file != 'img' ) { $image_array[$i]['url'] = $relative_dir . $file; $image_array[$i]['last_modified'] = date ("F d YH:i:s", filemtime($absolute_dir . '/' . $file)); } $i++; } closedir($handle); } 
+6
file php
source share
3 answers

If you want to do this completely in PHP, you should find all the files and their last modification times:

 $images = array(); foreach (scandir($folder) as $node) { $nodePath = $folder . DIRECTORY_SEPARATOR . $node; if (is_dir($nodePath)) continue; $images[$nodePath] = filemtime($nodePath); } arsort($images); $newest = array_slice($images, 0, 5); 
+13
source share

If you are really only interested in photos, you can use glob () instead of soulmerge scandir:

 $images = array(); foreach (glob("*.{png,jpg,jpeg}", GLOB_BRACE) as $filename) { $images[$filename] = filemtime($filename); } arsort($images); $newest = array_slice($images, 0, 5); 
+2
source share

Or you can create a function for the last 5 files in a specified folder.

 private function getlatestfivefiles() { $files = array(); foreach (glob("application/reports/*.*", GLOB_BRACE) as $filename) { $files[$filename] = filemtime($filename); } arsort($files); $newest = array_slice($files, 0, 5); return $newest; } 

btw im using a CI structure. Hooray!

+1
source share

All Articles