1. <?php
  2. /**
  3. * Sanitizes user input with rate limiting for isolated environments.
  4. *
  5. * @param array $data The array of user input data.
  6. * @param int $rateLimit The maximum number of requests allowed per time window (e.g., 60 seconds).
  7. * @param int $timeWindow The time window in seconds for rate limiting.
  8. * @return array The sanitized data. Returns an empty array if rate limited.
  9. */
  10. function sanitizeAndRateLimit(array $data, int $rateLimit, int $timeWindow): array
  11. {
  12. // Rate limiting implementation (using a simple in-memory counter)
  13. $rateLimitCounter = [];
  14. $now = time();
  15. // Clean and validate the input data
  16. $sanitizedData = [];
  17. foreach ($data as $key => $value) {
  18. if (is_array($value)) {
  19. $sanitizedData[$key] = sanitizeAndRateLimit($value, $rateLimit, $timeWindow); // Recursive call for nested arrays
  20. continue;
  21. }
  22. $sanitizedData[$key] = trim(htmlspecialchars($value, ENT_QUOTES, 'UTF-8')); // Basic sanitization: trim whitespace and escape HTML entities
  23. }
  24. // Rate limiting check
  25. if (!isset($rateLimitCounter[$now])) {
  26. $rateLimitCounter[$now] = $rateLimit;
  27. }
  28. if ($rateLimitCounter[$now] > 0) {
  29. $rateLimitCounter[$now]--;
  30. } else {
  31. // Rate limit exceeded
  32. error_log("Rate limit exceeded"); // Log the event
  33. return []; // Return empty array to indicate rate limit exceeded.
  34. }
  35. return $sanitizedData;
  36. }
  37. // Example usage:
  38. /*
  39. $userInput = $_POST; // Or $_GET, etc.
  40. $sanitizedInput = sanitizeAndRateLimit($userInput, 10, 60); // Rate limit: 10 requests per 60 seconds
  41. if (!empty($sanitizedInput)) {
  42. // Process the sanitized data
  43. print_r($sanitizedInput);
  44. } else {
  45. // Handle rate limit exceeded
  46. echo "Rate limit exceeded. Please try again later.";
  47. }
  48. */
  49. ?>

Add your comment