1

Suppose there's a directory named "abc"

This directory contains number of files. Out of all these files, I just want latest "X" or latest 15 files in an array(if possible using glob function) in php.

Every help will be greatly appreciable.

gehlotparesh
  • 142
  • 3
  • 13

3 Answers3

2
// directory for searching files

$dir = "/etc/php5/*";

// getting files with specified four extensions in $files

$files = glob($dir."*.{extension1,extension2,extension3,extension4}", GLOB_BRACE);

// will get filename and filetime in $files

$files = array_combine($files, array_map("filemtime", $files));

// will sort files according to the values, that is "filetime"

arsort($files);

// we don't require time for now, so will get only filenames(which are as keys of array)

$files = array_keys($files);

$starting_index = 0;
$limit = 15;

// will limit the resulted array as per our requirement

$files = array_slice($files, $starting_index,$limit);

// will print the final array

echo "Latest $limit files are as below : ";
print_r($files);

Please improve me, if am wrong

Fid
  • 462
  • 4
  • 21
gehlotparesh
  • 142
  • 3
  • 13
  • This works great. I know this is a bit old, but you should put the code into tags. – Fid Jul 01 '19 at 16:33
0

Use the function posted here: http://code.tutsplus.com/tutorials/quick-tip-loop-through-folders-with-phps-glob--net-11274

    $dir = "/etc/php5/*";

    // Open a known directory, and proceed to read its contents
    foreach(glob($dir) as $file) 
    {
        echo "filename: $file : filetype: " . filetype($file) . "<br />";
    }

And use filetime() function inside your foreach loop as an IF statement.: http://php.net/manual/en/function.filemtime.php

odedta
  • 2,430
  • 4
  • 24
  • 51
0

One way to do this and it's better than glob is to use the RecursiveDirectoryIterator

  $dir = new \RecursiveDirectoryIterator('path/to/folder', \FilesystemIterator::SKIP_DOTS);
    $it  = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::SELF_FIRST);
    $it->setMaxDepth(99); // search for other folders and they child folders
    $files = [];

    foreach ($it as $file) {
        if ($file->isFile()) {
            var_dump($file);
        }
    }

or if you still want to do it with glob

$files = glob('folder/*.{jpg,png,gif}', GLOB_BRACE);
foreach($files as $file) {
   var_dump($file);
}
Stanimir Dimitrov
  • 1,872
  • 2
  • 20
  • 25