企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
通过包来安装,点下面链接,注意看里面信息也有demo https://packagist.org/packages/geoip2/geoip2#v2.13.0 我是项目更目录通过以下命令安装 ~~~ composer require geoip2/geoip2:~2.0 ~~~ ![](https://img.kancloud.cn/ae/3b/ae3b8c0f56d79792f5e00f12f092c4c4_499x514.png) 安装比较简单,主要是拿到那个地区数据库,demo里面 ~~~ $reader = new Reader('/usr/local/share/GeoIP/GeoIP2-City.mmdb'); ~~~ GeoIP2-City.mmdb这个就是数据库 供应商有收费和免费的,我们用免费就好,特别精准就要收费的,需要在这个网站注册个账号,随便填 https://www.maxmind.com/en/accounts 注册成功后可以到这里下载你需要的数据库,数据库是离线的,可能过个几年数据就比较老了,需要更新,如果不想注册不拿最新的话,网上下载的也是老的,定位省份城市不准,我试过了, demo也提供自动更新,但是我比较赶时间,目前用的还可以,就不搞了,不然下次再手动下载一份替换即可 ![](https://img.kancloud.cn/fe/1a/fe1a90743d9b66470663a2b750d57e73_1695x700.png) 文件下载之后,用后缀.mmdb的文件就好 ,以下是我的代码,tp6框架 ~~~ public function getIpAddress($last_ip) { if (empty($last_ip)) { return ''; } try { $reader = new Reader(app()->getRootPath()."/public/xxxx/GeoLite2-City.mmdb"); $record = $reader->city($last_ip); // $country = empty($record->country->names['zh-CN'])?(empty($record->country->name)?'':$record->country->name):$record->country->names['zh-CN']; // $province = empty($record->mostSpecificSubdivision->names['zh-CN'])?(empty($record->mostSpecificSubdivision->name)?'':$record->mostSpecificSubdivision->name):$record->mostSpecificSubdivision->names['zh-CN']; // $city = empty($record->city->names['zh-CN'])?(empty($record->city->name)?'':$record->city->name):$record->city->names['zh-CN']; $country = $record->country->name??''; $province = $record->mostSpecificSubdivision->name??''; $city = $record->city->name??''; return $country.' '.$province.' '.$city; } catch (\MaxMind\Db\InvalidDatabaseException $e) { // return $e->getMessage(); return ''; } catch (\GeoIp2\Exception\AddressNotFoundException $e) { // return $e->getMessage(); return ''; } // halt($record); // print("country". "<br>"); // 'US' // print($record->country->isoCode . "\n"); // 'US' // print($record->country->name . "\n"); // 'United States' // print($record->country->names['zh-CN'] . "\n"); // '美国' // print("mostSpecificSubdivision". "<br>"); // 'US' // print($record->mostSpecificSubdivision->name . "\n"); // 'Minnesota' //// print($record->mostSpecificSubdivision->names['zh-CN'] . "\n"); // 'Minnesota' // print($record->mostSpecificSubdivision->isoCode . "\n"); // 'MN' // print("city". "<br>"); // 'US' // print($record->city->name . "\n"); // 'Minneapolis' //// print($record->city->names['zh-CN'] . "\n"); // 'Minneapolis' // // print($record->postal->code . "\n"); // '55455' // // print($record->location->latitude . "\n"); // 44.9733 // print($record->location->longitude . "\n"); // -93.2323 // // print($record->traits->network . "\n"); // '128.101.101.101/32' } ~~~