1. <?php
  2. /**
  3. * Function to apply rate limiting to JSON responses.
  4. *
  5. * @param array $data The data to be returned as JSON.
  6. * @param int $limit The maximum number of requests allowed within a time window (in seconds).
  7. * @param int $window The time window in seconds.
  8. * @param string $key The key to store the request timestamp for the user/IP.
  9. * @return array|string The modified data to be returned as JSON, or an error message.
  10. */
  11. function applyRateLimit(array $data, int $limit, int $window, string $key)
  12. {
  13. // Session storage for request timestamps
  14. if (!session_id()) {
  15. session_start();
  16. }
  17. // Check if the user/IP has exceeded the rate limit
  18. if (isset($_SESSION[$key])) {
  19. $lastRequest = $_SESSION[$key];
  20. $currentTime = time();
  21. if ($currentTime - $lastRequest < $window) {
  22. return ['error' => 'Rate limit exceeded. Please try again later.']; // Return an error message
  23. }
  24. }
  25. // Update the request timestamp
  26. $_SESSION[$key] = $currentTime;
  27. return $data; // Return the data
  28. }
  29. /**
  30. * Example usage: Simulate a API endpoint.
  31. *
  32. * @param array $requestData The incoming request data.
  33. * @return string The JSON response.
  34. */
  35. function apiEndpoint(array $requestData): string
  36. {
  37. // Simulate some processing
  38. sleep(0.1);
  39. try {
  40. $data = applyRateLimit($requestData, 10, 5, 'user_request'); // Limit to 10 requests every 5 seconds
  41. //If rate limit is exceeded, apply rate limiting function will return error message.
  42. if(isset($data['error'])){
  43. return json_encode($data); // Return error message as JSON
  44. }
  45. return json_encode($data); // Return the data as JSON
  46. } catch (Exception $e) {
  47. return json_encode(['error' => 'An unexpected error occurred: ' . $e->getMessage()]); // Return error as JSON
  48. }
  49. }
  50. // Example usage (for testing):
  51. if (isset($_POST['data'])) {
  52. $requestData = json_decode($_POST['data'], true);
  53. $response = apiEndpoint($requestData);
  54. echo $response;
  55. }
  56. ?>

Add your comment