<?php/*** 防火墙中间件*/require_once __DIR__ . '/Firewall.php';class FirewallMiddleware{public $firewall;public function __construct(){$this->firewall = new Ip2RegionFirewall();}/*** 处理请求*/public function handle(){$ip = $this->getClientIP();$result = $this->firewall->checkAccess($ip);if (!$result['allow']) {$this->showBlockedPage($result);return false;}return true;}/*** 获取客户端真实 IP*/public function getClientIP(){$keys = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'];foreach ($keys as $key) {if (!empty($_SERVER[$key])) {$ips = explode(',', $_SERVER[$key]);foreach ($ips as $ip) {$ip = trim($ip);if (filter_var($ip, FILTER_VALIDATE_IP)) {return $ip;}}}}return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';}/*** 显示禁止访问页面*/private function showBlockedPage($result){http_response_code(403);header('Content-Type: text/html; charset=utf-8');$location = $result['location'] ?? [];$region = trim($location['country'] . ' ' . $location['province'] . ' ' . $location['city']);$ip = $this->getClientIP();echo <<<HTML<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>访问被拒绝</title><style>body{font-family:Arial,sans-serif;background:#f5f5f5;display:flex;justify-content:center;align-items:center;height:100vh;margin:0}.container{background:white;padding:40px;border-radius:10px;box-shadow:0 2px 10px rgba(0,0,0,0.1);text-align:center;max-width:500px}h1{color:#e74c3c;margin-bottom:20px}p{color:#666;line-height:1.6}.info{background:#f8f9fa;padding:15px;border-radius:5px;margin:20px 0;text-align:left}.info-item{margin:8px 0;color:#555}.label{font-weight:bold;color:#333}</style></head><body><div class="container"><h1>🚫 访问被拒绝</h1><p>抱歉,根据您的地理位置,无法访问此服务。</p><div class="info"><div class="info-item"><span class="label">您的 IP:</span>{$ip}</div><div class="info-item"><span class="label">所在地区:</span> {$region}</div></div><p style="font-size:12px;color:#999;">如有疑问,请联系网站管理员</p><p style="font-size:12px;color:#999;">开源地址:<a href="https://gitee.com/qcod/phpfirewall" target="_blank">https://gitee.com/qcod/phpfirewall</a></p></div></body></html>HTML;exit();}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。