| 1 |
<?php |
| 2 |
|
| 3 |
namespace BerqWP; |
| 4 |
|
| 5 |
class RateLimiter |
| 6 |
{ |
| 7 |
private $limit; |
| 8 |
private $timeWindow; // In seconds |
| 9 |
private $storagePath; |
| 10 |
|
| 11 |
public function __construct($limit, $timeWindow, $storagePath) |
| 12 |
{ |
| 13 |
$this->limit = $limit; |
| 14 |
$this->timeWindow = $timeWindow; // e.g. 60 seconds for 1 minute |
| 15 |
$this->storagePath = rtrim($storagePath, '/') . '/'; |
| 16 |
} |
| 17 |
|
| 18 |
public function isRateLimited($clientIdentifier) |
| 19 |
{ |
| 20 |
if (!is_dir($this->storagePath)) { |
| 21 |
mkdir($this->storagePath, 0755, true); |
| 22 |
} |
| 23 |
|
| 24 |
$filePath = $this->storagePath . md5($clientIdentifier) . '.json'; |
| 25 |
|
| 26 |
if (!file_exists($filePath)) { |
| 27 |
// Create a new entry if it doesn't exist |
| 28 |
$this->createLog($filePath); |
| 29 |
return false; // Not rate limited |
| 30 |
} |
| 31 |
|
| 32 |
// Read the log file |
| 33 |
$logData = json_decode(file_get_contents($filePath), true); |
| 34 |
$currentTime = time(); |
| 35 |
|
| 36 |
if (!is_array($logData)) { |
| 37 |
$logData = []; |
| 38 |
} |
| 39 |
|
| 40 |
// Remove old entries from the time window |
| 41 |
$logData = array_filter($logData, function($timestamp) use ($currentTime) { |
| 42 |
return ($currentTime - $timestamp) <= $this->timeWindow; |
| 43 |
}); |
| 44 |
|
| 45 |
// Check if the limit is reached |
| 46 |
if (count($logData) >= $this->limit) { |
| 47 |
return true; // Rate limited |
| 48 |
} |
| 49 |
|
| 50 |
// Otherwise, add the new timestamp and update the log |
| 51 |
$logData[] = $currentTime; |
| 52 |
file_put_contents($filePath, json_encode($logData)); |
| 53 |
return false; |
| 54 |
} |
| 55 |
|
| 56 |
private function createLog($filePath) |
| 57 |
{ |
| 58 |
$logData = [time()]; |
| 59 |
file_put_contents($filePath, json_encode($logData)); |
| 60 |
} |
| 61 |
} |
| 62 |
|