Content · Web Development · PHP

Cursor-Based API Pagination

Use a stable sort key and encoded continuation token instead of a growing.

1 views Published Oct 17, 2026 Updated Oct 17, 2026 admin

Use a stable sort key and encoded continuation token instead of a growing offset. The examples separate the essential operation from the conditions a production implementation must enforce.

What It Does


Use a stable sort key and encoded continuation token instead of a growing offset.

Prerequisites


Use a dedicated development environment with test accounts and records. Separate authorization, validation and error handling from response formatting; never copy demonstration-only secrets into production.

Example 1: Core Behavior


The first example isolates the core operation so its result is easy to understand.

<?php
$lastId=40; $pageSize=10;
$values=['after'=>$lastId,'limit'=>$pageSize];
echo 'SELECT id FROM items WHERE id > :after ORDER BY id ASC LIMIT :limit';
echo json_encode($values);

Example 2: Alternative or Failure Case


The second example demonstrates an alternative outcome, rule or failure condition.

<?php
$cursor=base64_encode(json_encode(['lastId'=>42,'v'=>1],JSON_THROW_ON_ERROR));
$data=json_decode(base64_decode($cursor,true),true,512,JSON_THROW_ON_ERROR);
echo (int)$data['lastId']; // Use a MAC for tamper resistance.

Practical Example: Applying the Rule


The practical example shows how to carry the same constraint into application code.

<?php
$records=[['id'=>3],['id'=>7],['id'=>12]]; $last=7;
$page=array_values(array_filter($records,fn(array $r):bool=>$r['id']>$last));
echo json_encode($page);

Important Behavior and Edge Cases


Enforce authorization and filter consistency across cursor pages; sign opaque cursors if clients must not modify them.

Comparison with Related Functions or Patterns


ApproachWhen it differs
Cursor-Based API PaginationUse a stable sort key and encoded continuation token instead of a growing offset.
Related API or patternOffset pagination is easier for small, static result sets.

Common Beginner Mistakes


MistakeCorrect approach
Using an unstable sort key and producing overlapping pagesEnforce authorization and filter consistency across cursor pages; sign opaque cursors if clients must not modify them.
Substituting a related API without checking its semanticsOffset pagination is easier for small, static result sets.

Key Takeaways


  • Use a stable sort key and encoded continuation token instead of a growing offset.
  • Enforce authorization and filter consistency across cursor pages; sign opaque cursors if clients must not modify them.
  • Offset pagination is easier for small, static result sets.

Select this API or pattern based on its documented behavior and the trust boundaries in your own application, and test all external integrations against their actual deployments.

Share this resourceSend this page to someone who may find it useful.