39 lines
1.0 KiB
PHP
39 lines
1.0 KiB
PHP
<?php
|
|
class RateLimiter {
|
|
private $db;
|
|
private $maxRequests = 3;
|
|
private $timeWindow = 30;
|
|
|
|
public function __construct($db) {
|
|
$this->db = $db;
|
|
}
|
|
|
|
public function isAllowed($ip, $action = 'post') {
|
|
$stmt = $this->db->prepare('
|
|
SELECT COUNT(*) FROM rate_limits
|
|
WHERE ip_address = ? AND action_type = ?
|
|
AND created_at > DATE_SUB(NOW(), INTERVAL ? SECOND)
|
|
');
|
|
$stmt->execute([$ip, $action, $this->timeWindow]);
|
|
$count = $stmt->fetchColumn();
|
|
|
|
if ($count >= $this->maxRequests) {
|
|
return false;
|
|
}
|
|
|
|
$stmt = $this->db->prepare('
|
|
INSERT INTO rate_limits (ip_address, action_type) VALUES (?, ?)
|
|
');
|
|
$stmt->execute([$ip, $action]);
|
|
|
|
return true;
|
|
}
|
|
|
|
public function cleanup() {
|
|
$stmt = $this->db->prepare('
|
|
DELETE FROM rate_limits
|
|
WHERE created_at < DATE_SUB(NOW(), INTERVAL ? SECOND)
|
|
');
|
|
$stmt->execute([$this->timeWindow]);
|
|
}
|
|
}
|