From e1dbd9889d63a959cdf4fc28ebc3d511617744d3 Mon Sep 17 00:00:00 2001 From: lkddi Date: Fri, 27 Feb 2026 12:24:46 +0800 Subject: [PATCH] =?UTF-8?q?Fix:=20=E4=BF=AE=E6=AD=A3ip2region=E8=B0=83?= =?UTF-8?q?=E7=94=A8=E6=96=B9=E5=BC=8F=EF=BC=8C=E6=94=B9=E7=94=A8getIpInfo?= =?UTF-8?q?()=E5=85=BC=E5=AE=B9=E5=90=84=E7=89=88=E6=9C=AC=EF=BC=8C?= =?UTF-8?q?=E5=B9=B6=E6=AD=A3=E7=A1=AE=E4=BC=A0=E5=85=A5xdb=E8=B7=AF?= =?UTF-8?q?=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Http/Controllers/UserController.php | 29 +++++++++++++++---------- 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/app/Http/Controllers/UserController.php b/app/Http/Controllers/UserController.php index a7fdb29..5700489 100644 --- a/app/Http/Controllers/UserController.php +++ b/app/Http/Controllers/UserController.php @@ -71,24 +71,29 @@ class UserController extends Controller $ipToLookup = $targetUser->login_ip ?: $targetUser->last_ip; if ($ipToLookup) { try { - $ip2r = new \Ip2Region(database_path('ip2region/ip2region.xdb')); - $raw = $ip2r->search($ipToLookup); // 格式: 国家|省份|城市|运营商 + $xdbPath = database_path('ip2region/ip2region.xdb'); + // 第一个参数为缓存策略,第二个为自定义 IPv4 数据库路径 + $ip2r = new \Ip2Region('file', $xdbPath); + $info = $ip2r->getIpInfo($ipToLookup); - if ($raw) { - $parts = explode('|', $raw); - // 去掉 "0" 占位符并组合省市 - $parts = array_filter($parts, fn($p) => $p !== '0' && $p !== ''); - $parts = array_values($parts); - $country = $parts[0] ?? ''; - $region = $parts[1] ?? ''; - $city = $parts[2] ?? ''; + if ($info) { + $country = $info['country'] ?? ''; + $province = $info['province'] ?? ''; + $city = $info['city'] ?? ''; + + // 过滤掉占位符 "0" + $province = ($province === '0') ? '' : $province; + $city = ($city === '0') ? '' : $city; if ($country === '中国') { - // 国内:显示 省份 城市(如果省市不同则都显示) - $data['location'] = trim($region . ($region !== $city ? ' ' . $city : '')); + $data['location'] = trim($province . ($province !== $city ? ' ' . $city : '')); } else { $data['location'] = $country ?: '未知区域'; } + + if (empty($data['location'])) { + $data['location'] = '未知区域'; + } } else { $data['location'] = '未知区域'; }