<?php
/**
* Function to apply rate limiting to JSON responses.
*
* @param array $data The data to be returned as JSON.
* @param int $limit The maximum number of requests allowed within a time window (in seconds).
* @param int $window The time window in seconds.
* @param string $key The key to store the request timestamp for the user/IP.
* @return array|string The modified data to be returned as JSON, or an error message.
*/
function applyRateLimit(array $data, int $limit, int $window, string $key)
{
// Session storage for request timestamps
if (!session_id()) {
session_start();
}
// Check if the user/IP has exceeded the rate limit
if (isset($_SESSION[$key])) {
$lastRequest = $_SESSION[$key];
$currentTime = time();
if ($currentTime - $lastRequest < $window) {
return ['error' => 'Rate limit exceeded. Please try again later.']; // Return an error message
}
}
// Update the request timestamp
$_SESSION[$key] = $currentTime;
return $data; // Return the data
}
/**
* Example usage: Simulate a API endpoint.
*
* @param array $requestData The incoming request data.
* @return string The JSON response.
*/
function apiEndpoint(array $requestData): string
{
// Simulate some processing
sleep(0.1);
try {
$data = applyRateLimit($requestData, 10, 5, 'user_request'); // Limit to 10 requests every 5 seconds
//If rate limit is exceeded, apply rate limiting function will return error message.
if(isset($data['error'])){
return json_encode($data); // Return error message as JSON
}
return json_encode($data); // Return the data as JSON
} catch (Exception $e) {
return json_encode(['error' => 'An unexpected error occurred: ' . $e->getMessage()]); // Return error as JSON
}
}
// Example usage (for testing):
if (isset($_POST['data'])) {
$requestData = json_decode($_POST['data'], true);
$response = apiEndpoint($requestData);
echo $response;
}
?>
Add your comment