I want to display files in my directory in browser. I know that this is possible using @opendir
and readdir
.. But what I want is to limit the numb
Cross-posting an example (also in this question) --
DirectoryIterator and LimitIterator are my new best friends, although glob
seems to prefilter more easily. You could also write a custom FilterIterator. Needs PHP > 5.1, I think.
No prefilter:
$dir_iterator = new DirectoryIterator($dir);
$paginated = new LimitIterator($dir_iterator, $page * $perpage, $perpage);
Glob prefilter:
$dir_glob = $dir . '/*.{jpg,gif,png}';
$dir_iterator = new ArrayObject(glob($dir_glob, GLOB_BRACE));
$dir_iterator = $dir_iterator->getIterator();
$paginated = new LimitIterator($dir_iterator, $page * $perpage, $perpage);
Then, do your thing:
foreach ($paginated as $file) { ... }
Note that in the case of the DirectoryIterator
example, $file
will be an instance of SplFileInfo, whereas glob
example is just the disk path.