通過獲取客戶端 IP、調用 IP 地址庫、識別 User-Agent 特徵,實現精準訪問控制:封禁特定省份、放行搜索引擎爬蟲、防止惡意采集。
function get_client_ip() {
if (isset($_SERVER)) {
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
$realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
} elseif (isset($_SERVER["HTTP_CLIENT_IP"])) {
$realip = $_SERVER["HTTP_CLIENT_IP"];
} else {
$realip = $_SERVER["REMOTE_ADDR"];
}
} else {
if (getenv("HTTP_X_FORWARDED_FOR")) {
$realip = getenv("HTTP_X_FORWARDED_FOR");
} elseif (getenv("HTTP_CLIENT_IP")) {
$realip = getenv("HTTP_CLIENT_IP");
} else {
$realip = getenv("REMOTE_ADDR");
}
}
// 可能包含多個 IP,取第一個
return trim(explode(',', $realip)[0]);
}
function isCrawler() {
$spiderAgents = [
'Baiduspider', 'Googlebot', '360Spider', 'Sogou web spider',
'YandexBot', 'bingbot', 'Bytespider', 'AhrefsBot',
'MJ12bot', 'SemrushBot', 'DotBot', 'Applebot',
'DuckDuckBot', 'SeznamBot', 'PetalBot'
];
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
foreach ($spiderAgents as $bot) {
if (stripos($ua, $bot) !== false) return true;
}
return false;
}
function check_ip_block() {
$ip = get_client_ip();
// 調用淘寶 IP 庫(或自建 GeoIP)
$url = "https://ip.taobao.com/service/getIpInfo.php?ip=$ip";
$json = @file_get_contents($url);
if (!$json) return; // 查詢失敗不阻擋
$data = json_decode($json, true);
if (($data['code'] ?? 1) !== 0) return;
$region = $data['data']['region'] ?? '';
// 封禁湖北,但放行爬蟲
if ($region === '湖北省' && !isCrawler()) {
exit('您的地區暫不提供服務'); // 或 header('Location: /blocked.html');
}
}
// 入口文件最早調用
check_ip_block();
geoip2/geoip2 Composer 包,毫秒級查詢,無外部依賴ipmatch() 或資料庫 INET_ATON() 範圍查詢ngx_http_geoip_module / limit_req / ModSecurity 更高效class IpGuardMiddleware {
public function handle($request, Closure $next) {
$ip = $request->ip();
if ($this->isBlocked($ip) && !$this->isWhitelistedBot($request->header('User-Agent'))) {
return response('Forbidden', 403);
}
return $next($request);
}
// ... 具體實現
}
應用層封禁靈活但有性能開銷,高併發建議下沉到 Nginx/防火牆層。