ThinkPHP 6 通過擴展庫快速集成 IP 地址定位功能。本文詳細說明安裝配置、IP 獲取、定位查詢、編碼處理、域名解析及生產環境優化全流程。
# 方式一:Composer 安裝 (推薦)
composer require thinkphp/extension-iplocation
# 方式二:手動下載
# 官網:https://www.thinkphp.cn/extend/223.html
# 解壓 IpLocation.php 至 extend/org/Net/IpLocation.php
下載地址:UTFWry.dat (UTF-8 版純真數據庫)
# 放置位置
extend/org/Net/UTFWry.dat # Linux 區分大小寫
# 或自定義路徑,實例化時指定
<?php
use think\Request;
// 內置方法:自動處理代理、CDN、IPv6
$ip = Request::ip();
// 獲取長整型 IP (便於範圍查詢)
$ipLong = Request::ip(true); // 返回 int
// 手動獲取 (不依賴 Request)
function getClientIp(): string {
$headers = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'];
foreach ($headers as $header) {
if (!empty($_SERVER[$header])) {
$ips = explode(',', $_SERVER[$header]);
return trim($ips[0]);
}
}
return '0.0.0.0';
}
<?php
use org\Net\IpLocation;
// 默認加載 UTFWry.dat
$ipLoc = new IpLocation();
$location = $ipLoc->getlocation('218.79.93.194');
/*
返回結構:
[
'ip' => '218.79.93.194',
'beginip' => '218.79.93.0',
'endip' => '218.79.93.255',
'country' => '中國',
'area' => '北京市 聯通'
]
*/
// 組合地址字符串
$address = $location['country'] . $location['area']; // "中國北京市 聯通"
// 自定義 IP 庫文件
$ipLoc = new IpLocation('MyIpWry.dat');
// GBK 編碼庫轉換
$address = iconv('gbk', 'utf-8', $location['country'] . $location['area']);
// 自動獲取當前訪問者 IP 定位
$location = $ipLoc->getlocation(); // 內部調用 Request::ip()
// 域名解析定位
$location = $ipLoc->getlocation('www.thinkphp.cn');
<?php
// app/service/IpLocationService.php
namespace app\service;
use org\Net\IpLocation;
use think\facade\Config;
class IpLocationService {
protected IpLocation $ipLocation;
public function __construct() {
$this->ipLocation = new IpLocation(Config::get('iplocation.db_path', 'UTFWry.dat'));
}
public function getLocation(string $ip = ''): array {
$location = $this->ipLocation->getlocation($ip ?: '');
return [
'ip' => $location['ip'],
'country' => $location['country'],
'region' => $location['area'],
'city' => $this->extractCity($location['area']),
'isp' => $this->extractIsp($location['area']),
'coordinates' => $this->getCoordinates($location['country'], $location['area']),
];
}
private function extractCity(string $area): string {
// 解析 "北京市 聯通" → "北京市"
return preg_replace('/\s+.*$/', '', $area);
}
private function extractIsp(string $area): string {
// 解析 "北京市 聯通" → "聯通"
return preg_replace('/^.*\s+/', '', $area);
}
private function getCoordinates(string $country, string $area): ?array {
// 對接高德/百度地圖 API 獲取經緯度
return null;
}
}
// config/iplocation.php
return [
'db_path' => env('IP_LOCATION_DB', root_path() . 'extend/org/Net/UTFWry.dat'),
'auto_update' => false,
'update_url' => 'https://github.com/out0fmemory/qqwry.dat/raw/main/qqwry.dat',
'cache_ttl' => 86400,
];
<?php
// app/middleware/GeoLocation.php
namespace app\middleware;
use app\service\IpLocationService;
use think\Response;
class GeoLocation {
protected IpLocationService $geo;
public function __construct(IpLocationService $geo) {
$this->geo = $geo;
}
public function handle($request, \Closure $next) {
$request->geo = $this->geo->getLocation();
return $next($request);
}
}
// 控制器直接使用
public function index(Request $request) {
$city = $request->geo['city'] ?? '未知';
// 基於城市推薦內容...
}
<?php
// app/command/UpdateIpDatabase.php
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Config;
class UpdateIpDatabase extends Command {
protected function configure() {
$this->setName('iplocation:update')
->setDescription('更新 IP 地址庫');
}
protected function execute(Input $input, Output $output) {
$url = Config::get('iplocation.update_url');
$path = Config::get('iplocation.db_path');
$content = @file_get_contents($url);
if ($content && file_put_contents($path, $content, LOCK_EX)) {
$output->writeln('IP 數據庫更新成功 ');
return 0;
}
$output->writeln('更新失敗 ');
return 1;
}
}
// 定時任務 (crontab)
// 0 3 * * 0 /www/server/php/74/bin/php think iplocation:update # 每週日凌晨 3 點更新
| 問題 | 原因 | 解決 |
|---|---|---|
| Linux 下找不到文件 | 大小寫敏感 | 文件名確認為 UTFWry.dat,非 utfwry.dat |
| 返回亂碼 | 庫為 GBK 編碼 | 使用 iconv('gbk','utf-8',...) 或換 UTF-8 庫 |
| 定位不準 (國外 IP 顯示國內) | 純真庫更新滯後 | 改用 IP2Location、MaxMind GeoIP2、高德/騰訊位置服務 API |
| 高併發下性能瓶頸 | 文件讀取鎖競爭 | 載入內存數組、Redis 緩存熱點 IP、Swoole 進程共享內存 |
ThinkPHP 整合 UTFWry 實現 IP 定位,核心步驟:安裝擴展 → 放置 UTF-8 庫 → 實例化 IpLocation → 調用 getlocation()。生產環境建議服務化封裝、中間件注入、定時更新庫、對接商業級地理編碼 API 以提升精度。