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 number of files in the list to a specific number and display next using pagination.
You could use scandir to read all the contents of the directory into an array. Then output the contents of the array based on the pagination value.
$offset = 10; //get this as input from the user, probably as a GET from a link
$quantity = 10; //number of items to display
$filelist = scandir('/mydir');
//get subset of file array
$selectedFiles = array_slice($filelist, $offset-1, $quantity);
//output appropriate items
foreach($selectedFiles as $file)
{
    echo '<div class="file">'.$file.'</div>'; 
}
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With