<?php
session_start();
$ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
// 1. 从文件中读取黑名单IP地址
$blacklist_file = fopen("/blacklist.txt", "r");
$blacklist = array();
while (($line = fgets($blacklist_file)) !== false) {
$blacklist[] = trim($line);
}
fclose($blacklist_file);
// 将攻击者IP地址添加到黑名单中
if (in_array($_SERVER['REMOTE_ADDR'], $blacklist)) {
die("停下您的攻击,您已被禁止访问!");
}
// 2. 访问频率限制
$count = 0;
$time = time() - 180; // 限制3分钟内的访问频率
$req_count_diff = 0; // 记录请求次数的变量
// 检查来自同一IP地址的请求频率
$access_log = file("/log");
foreach ($access_log as $line) {
$tokens = explode(" ", $line);
$timestamp = strtotime($tokens[3]);
if (($tokens[0] == $ip) && ($timestamp > $time)) {
$count++;
$req_count_diff++;
}
}
// 如果访问频率超过限制,则延迟3秒
if ($count > 100) {
sleep(3);
}
// 3. 用户行为分析
if ($_SESSION['last_request']) {
$last_request = $_SESSION['last_request'];
$req_count_diff = $req_count_diff - $last_request['req_count'];
$ua_diff = strcmp($last_request['user_agent'], $user_agent);
// 如果请求异常,则将IP地址添加到黑名单中
if (($ua_diff !== 0) || ($req_count_diff >= 100)) {
$blacklist_file = fopen("/blacklist.txt", "a");
fwrite($blacklist_file, "$ip\n");
fclose($blacklist_file);
die("Your IP address has been banned from accessing this website.");
}
}
// 记录最后一个请求
$_SESSION['last_request'] = array(
"req_count" => $req_count_diff,
"user_agent" => $user_agent
);
// 正常的页面渲染代码
echo "Hello, World!";
?>
PHP------防止DDos和CC攻击
共计 0 条评论,点此发表评论