1. <?php
  2. /**
  3. * Handles paginated results from web forms with rate limiting.
  4. *
  5. * @param array $data The array of data to paginate.
  6. * @param int $pageSize The number of results per page.
  7. * @param int $page The current page number.
  8. * @param int $rateLimit The maximum number of requests allowed per time period (in seconds).
  9. * @param int $timePeriod The time period for rate limiting (in seconds).
  10. * @return array|false An array containing the paginated data, total pages, and message, or false on error.
  11. */
  12. function paginateWithRateLimit(array $data, int $pageSize, int $page, int $rateLimit, int $timePeriod): array|false
  13. {
  14. // Rate limiting implementation
  15. $ip = $_SERVER['REMOTE_ADDR'];
  16. $rateLimitKey = "rate_limit_" . $ip;
  17. if (!isset($_SESSION[$rateLimitKey])) {
  18. $_SESSION[$rateLimitKey] = [];
  19. }
  20. $startTime = time();
  21. $requests = array_count_values($_SESSION[$rateLimitKey]);
  22. // Clean up old requests
  23. foreach ($requests as $key => $timestamp) {
  24. if ($startTime - $timestamp > $timePeriod) {
  25. unset($_SESSION[$rateLimitKey][$key]);
  26. }
  27. }
  28. if (count($_SESSION[$rateLimitKey]) >= $rateLimit) {
  29. return ['message' => 'Rate limit exceeded. Please try again later.', 'data' => []];
  30. }
  31. // Add current request
  32. $_SESSION[$rateLimitKey][] = time();
  33. $start = ($page - 1) * $pageSize;
  34. $end = $start + $pageSize;
  35. if ($start < count($data)) {
  36. $result = array_slice($data, $start, $pageSize);
  37. $totalResults = count($data);
  38. $totalPages = ceil($totalResults / $pageSize);
  39. return [
  40. 'data' => $result,
  41. 'totalResults' => $totalResults,
  42. 'totalPages' => $totalPages,
  43. 'currentPage' => $page,
  44. 'pageSize' => $pageSize,
  45. 'message' => '', // No message on success
  46. ];
  47. } else {
  48. return ['message' => 'No more results.', 'data' => []];
  49. }
  50. }
  51. //Example Usage (for testing)
  52. /*
  53. $data = range(1, 100);
  54. $pageSize = 10;
  55. $page = 1;
  56. $rateLimit = 5;
  57. $timePeriod = 60; // seconds
  58. $result = paginateWithRateLimit($data, $pageSize, $page, $rateLimit, $timePeriod);
  59. if ($result) {
  60. echo "<pre>";
  61. print_r($result);
  62. echo "</pre>";
  63. } else {
  64. echo "Error during pagination.";
  65. }
  66. */
  67. ?>

Add your comment