在项目中需要使用ip获取归属地
目录
获取国外ip归属地
GeoIP2(MaxMind,适合海外 IP)
安装
在项目目录下命令行执行以下命令:
bash
composer require maxmind-db/reader

安装后,更新composer自动加载
bash
composer dump-autoload --o
下载ip数据
网址https://www.maxmind.com/en/accounts/1283983/geoip/downloads
需要注册账号,使用邮箱就行,免费的。
尝试了只能下载国家级的数据,不允许下载城市级的数据。
封装请求
在fastadmin中封装到common下的library目录下,
调用安装的maxmind库识别ip。
示例如下:
php
<?php
namespace app\common\library;
use MaxMind\Db\Reader;
class GeoIP2
{
/**
* 获取IP归属地信息
* @param string $ip 要查询的IP地址(空则取客户端IP)
* @return array 归属地数组|错误信息
*/
public static function getLocation($ip = '')
{
// 验证IP格式
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
return [
'code' => 0,
'msg' => 'IP地址格式错误',
'data' => []
];
}
try {
// 初始化并查询
$dbPath = ROOT_PATH . 'public/assets/data/GeoLite2-Country.mmdb';
$reader = new Reader($dbPath);
$record = $reader->get($ip);
$reader->close();
return [
'code' => 1,
'msg' => '查询成功',
'data' => [
'ip' => $ip,
'country' => $record['country']['names']['zh-CN'] ?? '未知',
'city' => $record['city']['names']['zh-CN'] ?? '未知',
'longitude' => $record['location']['longitude'] ?? 0, // 经度
'latitude' => $record['location']['latitude'] ?? 0 // 纬度
]
];
} catch (\Exception $e) {
// 捕获异常(如IP库异常、查询失败等)
return [
'code' => 0,
'msg' => '查询失败:' . $e->getMessage(),
'data' => []
];
}
}
}
调用
在控制器中调用封装方法,示例如下:
php
public function test()
{
$res = GeoIP2::getLocation('89.44.236.93');
return json_encode($res);
}
返回结果
测试国外ip,返回结果:
bash
{
"code": 1,
"msg": "查询成功",
"data": {
"ip": "89.44.236.93",
"country": "意大利",
"city": "未知",
"longitude": 0,
"latitude": 0
}
}
总结
需要借用GeoIP2库三方类库通过其中的ip库进行识别。