有时候服务器被采集或蜘蛛抓取或被攻击,那么就需要对应的禁止ip访问的方法了
function ifIpAdd(){
// 获取客户端的 IP 地址
$client_ip = $_SERVER['REMOTE_ADDR'];
// 定义要禁止的 IP 前缀数组
$blocked_prefixes = [
'47.79.',
'47.82.',
'114.0.1823.',
// 可以添加更多要禁止的 IP 前缀
];
// 检查客户端 IP 是否以任何一个禁止的前缀开头
foreach ($blocked_prefixes as $prefix) {
$prefix_length = strlen($prefix);
if (substr($client_ip, 0, $prefix_length) === $prefix) {
// 设置要跳转的 URL
$new_url = 'https://www.baidu.com';
// 发送 HTTP 重定向头
header("Location: $new_url");
exit;
}
}
}
还有指定ip和指定开头一起的
<?php
// 获取客户端的 IP 地址
$client_ip = $_SERVER['REMOTE_ADDR'];
// 定义允许跳转的具体 IP 地址数组
$allowed_ips = [
'192.168.1.100',
'10.0.0.5',
// 可以添加更多允许的 IP 地址
];
// 定义允许跳转的 IP 前缀数组
$allowed_prefixes = [
'47.79.',
'172.16.',
// 可以添加更多允许的 IP 前缀
];
// 检查客户端 IP 是否在允许的具体 IP 列表中
$is_allowed = in_array($client_ip, $allowed_ips);
// 如果不在具体 IP 列表中,检查是否以允许的前缀开头
if (!$is_allowed) {
foreach ($allowed_prefixes as $prefix) {
$prefix_length = strlen($prefix);
if (substr($client_ip, 0, $prefix_length) === $prefix) {
$is_allowed = true;
break;
}
}
}
if ($is_allowed) {
// 设置要跳转的 URL
$new_url = 'https://www.baidu.com';
// 发送 HTTP 重定向头
header("Location: $new_url");
// 终止当前脚本的执行
exit;
} else {
echo "您的 IP 地址不被允许进行跳转。";
}
?>