Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VIew files in directory with pagination - php

Tags:

php

pagination

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.

like image 842
Alfred Avatar asked Feb 24 '11 14:02

Alfred


2 Answers

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>'; 
}
like image 193
Surreal Dreams Avatar answered Nov 01 '22 08:11

Surreal Dreams


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.

like image 33
drzaus Avatar answered Nov 01 '22 08:11

drzaus