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.
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.
// 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
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
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);
}