<?php
class RequestThrottler {
private $request_headers = []; // Array to store request header counts
private $rate_limit; // Request rate limit (e.g., 10 requests per minute)
private $window; // Time window for rate limiting (in seconds)
public function __construct(array $allowed_headers, int $rate_limit, int $window = 60) {
$this->request_headers = $allowed_headers;
$this->rate_limit = $rate_limit;
$this->window = $window;
}
public function isAllowed(array $headers): bool {
// Reset counts for headers not in the allowed list.
foreach ($this->request_headers as $header) {
if (!isset($this->request_headers[$header])) {
$this->request_headers[$header] = 0;
}
}
$now = time();
// Remove expired entries from the window.
$this->cleanupWindow($now);
// Check if the header count exceeds the rate limit.
foreach ($headers as $header => $value) {
if (isset($this->request_headers[$header])) {
$this->request_headers[$header]++;
if ($this->request_headers[$header] > $this->rate_limit) {
return false; // Rate limit exceeded
}
}
}
return true; // Request allowed
}
private function cleanupWindow(int $now): void {
foreach ($this->request_headers as $header => $count) {
if ($now - $this->window > 0) {
$this->request_headers[$header] = 0;
}
}
}
}
Add your comment