网站防cc php代码
[]// 存储IP访问记录的目录(确保PHP有写入权限)
define('IP_LOG_DIR', '/path/to/ip_logs/');
// 限制每个IP每分钟的请求次数
define('REQUEST_LIMIT', 100);
define('TIME_FRAME', 60); // 秒
function isRequestAllowed($ip) {
$logFile = IP_LOG_DIR . $ip;
$currentTime = time();
// 清理过期的记录
if (file_exists($logFile)) {
$log = file_get_contents($logFile);
$logEntries = explode("\n", $log);
$filteredEntries = [];
foreach ($logEntries as $entry) {
if ($entry) {
list($timestamp) = explode('|', $entry);
if (($currentTime - $timestamp) < TIME_FRAME) {
$filteredEntries[] = $entry;
}
}
}
$log = implode("\n", $filteredEntries);
} else {
$log = '';
}
// 检查是否超过限制
if (substr_count($log, "\n") >= REQUEST_LIMIT) {
return false;
}
// 记录当前请求
$log .= $currentTime . '|' . $currentTime . "\n";
file_put_contents($logFile, $log);
return true;
}
// 获取客户端IP
function getClientIP() {
if (isset($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP']) {
return $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']) {
// 处理可能存在的多个IP
$ipList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
return trim($ipList[0]);
} elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR']) {
return $_SERVER['REMOTE_ADDR'];
}
return 'UNKNOWN';
}
$clientIP = getClientIP();
// 检查请求是否被允许
if (!isRequestAllowed($clientIP)) {
header('HTTP/1.1 429 Too Many Requests');
echo '请求过于频繁,请稍后再试。';
exit;
}
// 继续处理正常的请求
?>[/]
拯救了 104 人的帖子