源代码已上传
https://download.csdn.net/download/chendongpu/19809982
下载composer
curl -sS https://getcomposer.org/installer | php
安装GeoIP2扩展包
php composer.phar require geoip2/geoip2:~2.0
下载GeoLite2免费版数据库
./GeoLite2-Country.mmdb
./GeoLite2-City.mmdb
下载完毕后共生成以下内容
-rw-rw-r-- 1 someuser someuser 63 Aug 11 17:03 composer.json
-rw-rw-r-- 1 someuser someuser 2.4K Aug 11 17:03 composer.lock
-rw-rw-r-- 1 someuser someuser 73M Aug 11 17:04 GeoLite2-City.mmdb
-rw-rw-r-- 1 someuser someuser 19M Aug 11 17:04 GeoLite2-Country.mmdb
drwxrwxr-x 4 someuser someuser 4.0K Aug 11 17:03 vendor/
如何使用GeoIP2-PHP
1:在PHP中引入Composer自动加载
require 'vendor/autoload.php';
如果不想使用Composer自动加载,也可以自定义,只需要按以下方式引入亦可。
require('/自定义路径/autoload.php');
2:实例化reader类并引入mmdb数据库
use GeoIp2\Database\Reader;
$reader = new Reader('./GeoLite2-City.mmdb');
到此,php版GeoIP2-PHP已可使用。
代码示例
<?php
require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;
// This creates the Reader object, which should be reused across
// lookups.
$reader = new Reader('./GeoLite2-City.mmdb');
// Replace "city" with the appropriate method for your database, e.g.,
// "country".
$record = $reader->city('128.101.101.101');
print($record->country->isoCode . "\n"); // 'US'
print($record->country->name . "\n"); // 'United States'
print($record->country->names['zh-CN'] . "\n"); // '..'
print($record->mostSpecificSubdivision->name . "\n"); // 'Minnesota'
print($record->mostSpecificSubdivision->isoCode . "\n"); // 'MN'
print($record->city->name . "\n"); // 'Minneapolis'
print($record->postal->code . "\n"); // '55455'
print($record->location->latitude . "\n"); // 44.9733
print($record->location->longitude . "\n"); // -93.2323