Files
botlimiter/classes/RateLimiter.php
2026-04-05 21:20:54 +03:00

41 lines
1.3 KiB
PHP

<?php
class RateLimiter
{
/**
* @param string $ip The IP to check
* @param string $action A unique string for the action (e.g., '404', 'verify_attempt')
* @param int $max_requests
* @param int $window seconds
* @return bool True if allowed, false if limit exceeded
*/
public static function checkIsRateLimited($ip, $action, $max_requests, $window)
{
// 1. Check if the Cache module is available
if (!Module::isInstalled('dbmemorycache') || !Module::isEnabled('dbmemorycache')) {
return false; // Not limited if we can't track it
}
$cache = Module::getInstanceByName('dbmemorycache');
if (!$cache) {
return false;
}
// 2. Generate unique key for this IP + Action
$cacheKey = hash('sha256', 'bot_limit_' . $action . '_' . $ip);
// 3. Get current count
$currentCount = 0;
if ($cache->existsValue($cacheKey)) {
$currentCount = (int) $cache->getValue($cacheKey);
}
$currentCount++;
// 4. Save back with the window (Resets timer on every hit = Sliding Window)
$cache->setValue($cacheKey, $currentCount, $window);
// 5. Return status
return ($currentCount > $max_requests);
}
}