<?php
/**
* Handles paginated results from web forms with rate limiting.
*
* @param array $data The array of data to paginate.
* @param int $pageSize The number of results per page.
* @param int $page The current page number.
* @param int $rateLimit The maximum number of requests allowed per time period (in seconds).
* @param int $timePeriod The time period for rate limiting (in seconds).
* @return array|false An array containing the paginated data, total pages, and message, or false on error.
*/
function paginateWithRateLimit(array $data, int $pageSize, int $page, int $rateLimit, int $timePeriod): array|false
{
// Rate limiting implementation
$ip = $_SERVER['REMOTE_ADDR'];
$rateLimitKey = "rate_limit_" . $ip;
if (!isset($_SESSION[$rateLimitKey])) {
$_SESSION[$rateLimitKey] = [];
}
$startTime = time();
$requests = array_count_values($_SESSION[$rateLimitKey]);
// Clean up old requests
foreach ($requests as $key => $timestamp) {
if ($startTime - $timestamp > $timePeriod) {
unset($_SESSION[$rateLimitKey][$key]);
}
}
if (count($_SESSION[$rateLimitKey]) >= $rateLimit) {
return ['message' => 'Rate limit exceeded. Please try again later.', 'data' => []];
}
// Add current request
$_SESSION[$rateLimitKey][] = time();
$start = ($page - 1) * $pageSize;
$end = $start + $pageSize;
if ($start < count($data)) {
$result = array_slice($data, $start, $pageSize);
$totalResults = count($data);
$totalPages = ceil($totalResults / $pageSize);
return [
'data' => $result,
'totalResults' => $totalResults,
'totalPages' => $totalPages,
'currentPage' => $page,
'pageSize' => $pageSize,
'message' => '', // No message on success
];
} else {
return ['message' => 'No more results.', 'data' => []];
}
}
//Example Usage (for testing)
/*
$data = range(1, 100);
$pageSize = 10;
$page = 1;
$rateLimit = 5;
$timePeriod = 60; // seconds
$result = paginateWithRateLimit($data, $pageSize, $page, $rateLimit, $timePeriod);
if ($result) {
echo "<pre>";
print_r($result);
echo "</pre>";
} else {
echo "Error during pagination.";
}
*/
?>
Add your comment