在项目中需要使用ip获取归属地
目录
获取国内ip归属地
使用三方库zoujingli/ip2region。
安装
在项目根目录执行命令:
bash
composer require zoujingli/ip2region
在composer.json中出现

安装完成,更新Composer自动加载
bash
composer dump-autoload -o
封装请求
在fastadmin中封装到common下的library目录下,
调用安装的zoujingli/ip2region库识别ip。
示例如下:
php
<?php
/**
* FastAdmin IP归属地查询工具类(基于ip2region)
* 路径:application/common/library/Ip2Region.php
*/
namespace app\common\library;
use think\Request;
class Ip2Region
{
/**
* 获取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 {
// 初始化ip2region并查询
$ip2region = new \Ip2Region();
// memorySearch是内存查询模式,速度最快
$result = $ip2region->memorySearch($ip);
// 解析查询结果(格式:国家|区域|省份|城市|运营商)
$region = explode('|', $result['region']);
$data = [
'ip' => $ip,
'country' => $region[0] ?? '未知', // 国家
'province' => $region[2] ?? '未知', // 省份(索引2)
'city' => $region[3] ?? '未知', // 城市(索引3)
'isp' => $region[4] ?? '未知', // 运营商(索引4)
'area' => $region[2] . ($region[3] ? '·' . $region[3] : '') // 省·市 简化显示
];
return [
'code' => 1,
'msg' => '查询成功',
'data' => $data
];
} catch (\Exception $e) {
// 捕获异常(如IP库异常、查询失败等)
return [
'code' => 0,
'msg' => '查询失败:' . $e->getMessage(),
'data' => []
];
}
}
}
调用
在控制器中调用封装的ip归属地方法,传入一个测试ip.
示例如下:
php
public function test()
{
$res = Ip2Region::getLocation('211.149.175.128');
return json_encode($res);
}
返回结果
bash
{
"code": 1,
"msg": "查询成功",
"data": {
"ip": "211.149.175.128",
"country": "中国",
"province": "成都市",
"city": "电信",
"isp": "未知",
"area": "成都市·电信"
}
}
但这个库主要针对国内,对于国外ip归属地返回信息少,并且有偏差
比如是美国ip,但返回显示为澳大利亚
总结
需要借用zoujingli/ip2region库三方类库通过其中的ip库进行识别。