开发者

PHP Filesystem Pagination

开发者 https://www.devze.com 2022-12-30 07:09 出处:网络
How does one paginate a large listing of files within a folder? I can\'t see any functions in the PHP documentation that mention any way to specify an \'offset\'. Both glob() and scandir() simply ret

How does one paginate a large listing of files within a folder?

I can't see any functions in the PHP documentation that mention any way to specify an 'offset'. Both glob() and scandir() simply return all the files in the folder, an开发者_开发问答d I'm afraid that won't be a good idea for a huge directory.

Is there any better way of doing this than simply going through all the files and chopping off the first X number of files? Note that I would like to have options for recursive traversal and using a glob() pattern.

Edit: I've looked a lot at LimitIterator, GlobIterator and RecursiveDirectoryIterator. They all seem nice but I have no idea where to even start if I was to combine them (The PHP SPL documentation is extremely sparse). I'm probably just over-thinking the problem.


You can paginate the results yourself, PHP returns a simple array, so you can keep a $offset and $limit variables so you know in which part of your array you are.

If you are in a web context, you can pass these around in GET parameters.


Just to put some code to what Francisco Soto said, paginate manually

$limit = 10;
$offset = (isset($_GET['offset'])) ? $_GET['offset'] : 0;
$dir = scandir($path);
for ($i = $offset; $i < $offset+$limit; $i++) {
    echo $dir[$i] . "<br />";
}
echo "<br />";
for ($i = 0; $i < count($dir); $i++) {
    echo "<a href='?offset=" . ($i*$limit) . "'>{$i}</a>";
}

VERY rough, untested code.


No, there isn't. Directories are just another type of streams, and this is how the "seek" operator is defined:

static int php_plain_files_dirstream_rewind(php_stream *stream, off_t offset, int whence, off_t *newoffs TSRMLS_DC)
{
    rewinddir((DIR *)stream->abstract);
    return 0;
}

You see it's just a rewind. So you must read the first n entries to read entry n + 1. If you want to be more efficient, you can read the whole directory the first time and use it as a cache (store e.g. in the session). Once you've read all, you go to offset n+1 in the stored array.

0

精彩评论

暂无评论...
验证码 换一张
取 消