# PHP如何禁止国内IP访问网站 在特定业务场景下,网站可能需要限制国内IP访问(如仅面向海外用户的服务)。本文将详细介绍通过PHP实现该功能的5种方案,并提供完整代码示例。 ## 一、基本原理 禁止特定地区IP访问的核心逻辑是: 1. 获取客户端IP 2. 判断IP所属国家/地区 3. 对国内IP返回403禁止访问 ## 二、获取客户端真实IP ```php function getClientIP() { $ip = ''; if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]; } elseif (isset($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } return trim($ip); }
require_once 'QQWry.dat'; function isChinaIP($ip) { $qqwry = new \lysenko\QQWry('QQWry.dat'); $result = $qqwry->query($ip); return $result['country'] === '中国'; } if (isChinaIP(getClientIP())) { header('HTTP/1.1 403 Forbidden'); exit('Access Denied'); }
优点:不依赖第三方API
缺点:需定期更新数据库
function checkIPCountry($ip) { $response = file_get_contents("http://ip-api.com/json/{$ip}?fields=countryCode"); $data = json_decode($response, true); return $data['countryCode'] === 'CN'; } if (checkIPCountry(getClientIP())) { http_response_code(403); die('Service not available in your region'); }
// 在PHP中验证CF-IPCountry头 if ($_SERVER['HTTP_CF_IPCOUNTRY'] === 'CN') { header('Location: /blocked.html', true, 302); exit; }
注意:需先启用Cloudflare的IP地理定位功能
geo $block_country { default 0; 1.0.1.0/24 1; # 中国IP段示例 1.0.2.0/23 1; } server { location / { if ($block_country) { return 403; } # PHP处理逻辑... } }
pecl install geoip2
use GeoIp2\Database\Reader; $ip = getClientIP(); $reader = new Reader('/path/to/GeoLite2-Country.mmdb'); try { $record = $reader->country($ip); if ($record->country->isoCode === 'CN') { header('HTTP/1.1 403 Forbidden'); include('forbidden.html'); exit; } } catch (Exception $e) { // 异常处理 }
$memcached = new Memcached(); $memcached->addServer('localhost', 11211); $cacheKey = 'ip_country_'.md5($ip); if ($result = $memcached->get($cacheKey)) { return $result === 'CN'; }
定时任务更新IP库:每周自动下载最新GeoIP数据库
边缘计算方案:在CDN层面实现地域封锁(Cloudflare/AWS WAF)
GitHub Gist示例 包含: - IP检测类 - 黑名单/白名单功能 - 日志记录模块 - 多语言错误页面
通过以上方案,开发者可以根据业务需求选择最适合的国内IP禁止访问实施方案。 “`
(注:实际字数约850字,可根据需要扩展具体实现细节或补充性能测试数据达到900字要求)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。