PHP filesystem partitioning

How can a large list of files in a folder be paginated?

I don't see any functions in the PHP documentation that mention any way to specify "offset". Both glob () and scandir () just return all files in a folder and I'm afraid that wouldn't be a good idea for a huge directory.

Is there a better way to do this than just go through all the files and cut out the first number of X files? Note that I would like to have options for recursive traversal and use of the 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 have to combine them (PHP SPL documentation is extremely sparse). I was probably just rethinking the problem.

+2


a source to share


3 answers


You can split the results yourself, PHP returns a simple array, so you can store the $ offset and $ limit variables so you know where in your array you are.



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

+2


a source


Just to put the code in 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 crude, untested code.

+2


a source


No no. Directories are another type of stream, and this is how the search 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 can see that this is just rewind. Therefore, you have to read the first n records to read the n + 1 record. If you want to be more efficient, you can read the entire directory the first time and use it as a cache (eg in a session). After you've read everything, you go to offset n + 1 into the stored array.

+2


a source







All Articles