From 8d735df6a84820d1bb9aa9c3fffc2627d2d4b110 Mon Sep 17 00:00:00 2001 From: WispX <1591788658@qq.com> Date: Wed, 18 Mar 2020 21:18:36 +0800 Subject: [PATCH] =?UTF-8?q?:sparkles:=20=E5=B0=81=E7=A6=81=20IP=20?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=E6=94=AF=E6=8C=81=E9=80=9A=E9=85=8D=E7=AC=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- application/http/middleware/Initialize.php | 38 +++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/application/http/middleware/Initialize.php b/application/http/middleware/Initialize.php index 94913026..85c832fb 100644 --- a/application/http/middleware/Initialize.php +++ b/application/http/middleware/Initialize.php @@ -24,11 +24,47 @@ class Initialize $banIp = $this->getConfig('ban_ip'); if ($banIp) { $ips = explode(',', str_replace(',', ',', $banIp)); - if (in_array($request->ip(), $ips)) { + if ($this->banIp($request->ip(), $ips)) { throw new HttpResponseException(Response::code(403)); } } return $next($request); } + + /** + * 拦截某个IP, 支持通配符 + * + * @param string $ip + * @param array $ips + * @return bool + */ + private function banIp(string $ip, array $ips) + { + $parts = explode('.', $ip); // 分段当前 IP + $ban = false; + foreach ($ips as $item) { + // 如果直接匹配到 + if ($item === $ip) { + $ban = true; + continue; + } + + if (strpos($item, '*') !== false) { + $array = explode('.', $item); + $check = true; + for ($i = 0; $i < count($array); $i++) { + if ($array[$i] !== '*' && $array[$i] !== $parts[$i]) { + $check = false; + break; + } + } + if ($check) { + $ban = true; + break; + } + } + } + return $ban; + } }