mkach/RateLimiter.php
Lain Iwakura c5ad7e8cb4
ok?
2025-07-24 05:58:36 +03:00

39 lines
1.0 KiB
PHP

<?php
class RateLimiter {
private $db;
private $maxRequests = 30;
private $timeWindow = 6;
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]);
}
}