VIew files in directory with pagination - php

前端 未结 6 1753
遇见更好的自我
遇见更好的自我 2020-12-30 15:06

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

6条回答
  •  长发绾君心
    2020-12-30 15:48

    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.

提交回复
热议问题