1. <?php
  2. class RequestThrottler {
  3. private $request_headers = []; // Array to store request header counts
  4. private $rate_limit; // Request rate limit (e.g., 10 requests per minute)
  5. private $window; // Time window for rate limiting (in seconds)
  6. public function __construct(array $allowed_headers, int $rate_limit, int $window = 60) {
  7. $this->request_headers = $allowed_headers;
  8. $this->rate_limit = $rate_limit;
  9. $this->window = $window;
  10. }
  11. public function isAllowed(array $headers): bool {
  12. // Reset counts for headers not in the allowed list.
  13. foreach ($this->request_headers as $header) {
  14. if (!isset($this->request_headers[$header])) {
  15. $this->request_headers[$header] = 0;
  16. }
  17. }
  18. $now = time();
  19. // Remove expired entries from the window.
  20. $this->cleanupWindow($now);
  21. // Check if the header count exceeds the rate limit.
  22. foreach ($headers as $header => $value) {
  23. if (isset($this->request_headers[$header])) {
  24. $this->request_headers[$header]++;
  25. if ($this->request_headers[$header] > $this->rate_limit) {
  26. return false; // Rate limit exceeded
  27. }
  28. }
  29. }
  30. return true; // Request allowed
  31. }
  32. private function cleanupWindow(int $now): void {
  33. foreach ($this->request_headers as $header => $count) {
  34. if ($now - $this->window > 0) {
  35. $this->request_headers[$header] = 0;
  36. }
  37. }
  38. }
  39. }

Add your comment