= $limit) { SecurityHelper::logSecurityEvent('rate_limit_exceeded', $userId, [ 'requests_count' => count($requests), 'limit' => $limit, 'time_window' => $timeWindow ]); return false; // Rate limit exceeded } // เพิ่ม request ปัจจุบัน $requests[] = $now; // บันทึกข้อมูลกลับ $data = ['requests' => array_values($requests)]; file_put_contents($file, json_encode($data), LOCK_EX); return true; } /** * ล้างข้อมูล rate limit สำหรับผู้ใช้ */ public static function clearRateLimit($userId) { $file = self::getRateLimitFile($userId); if (file_exists($file)) { unlink($file); } } /** * ล้างข้อมูล rate limit ที่หมดอายุ */ public static function cleanupExpiredLimits() { $logsDir = __DIR__."/../../logs"; if (!is_dir($logsDir)) { return; } $files = glob($logsDir."/rate_limit_*.json"); $now = time(); $maxAge = defined('RATE_LIMIT_WINDOW') ? RATE_LIMIT_WINDOW : 60; foreach ($files as $file) { if (filemtime($file) < ($now - $maxAge * 2)) { unlink($file); } } } }