code-orange / lumen-geoip
Lumen 的 GeoIP
v3.0.0
2017-11-21 09:53 UTC
Requires
- php: >=5.5.9
- geoip2/geoip2: ^2.4
README
根据网站访问者的 IP 地址确定其地理位置。
安装
要安装此包,只需通过 composer 安装即可
$ composer require code-orange/lumen-geoip
服务提供者
接下来,打开 bootstrap/app.php
并在“注册服务提供者”部分下添加
... $app->register(CodeOrange\GeoIP\GeoIPServiceProvider::class);
更新 MaxMind GeoLite2 城市数据库
在项目的根目录下从命令行运行此命令
$ php artisan geoip:update
用法
GeoIP 将尝试使用以下 http 头来确定 IP:HTTP_CLIENT_IP
、HTTP_X_FORWARDED_FOR
、HTTP_X_FORWARDED
、HTTP_X_CLUSTER_CLIENT_IP
、HTTP_FORWARDED_FOR
、HTTP_FORWARDED
、REMOTE_ADDR
,按此顺序。可选地,您可以将 IP 设置为唯一的参数来设置它。
$record = app()->geoip->getLocation('232.223.11.11'); $record = GeoIP::getLocation('232.223.11.11'); // If you have enabled facades 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
其他方法
这些方法也可以在您的应用程序中使用。
app()->geoip->checkIp($ip) // Checks IP to make sure IP is a valid IPv4 or IPv6 address and not within a private or reserved range app()->geoip->getIp() // Returns the detected client IP
默认位置数据
当未检测到 IP 时,它将被设置为 127.0.0.1,这将最终抛出异常。如果您不在生产环境中,您的记录将默认为以下数据。
array ( "ip" => "232.223.11.11", "isoCode" => "US", "country" => "United States", "city" => "New Haven", "state" => "CT", "postal_code" => "06510", "lat" => 41.28, "lon" => -72.88, "timezone" => "America/New_York", "continent" => "NA", "default" => false );
变更日志
v3.0.0
- 添加了对 Lumen 5.5 的支持
v2.0.0
- 简化了命名空间
- 添加了对 Facade 的支持
- 在开发模式下添加了默认位置
- 修复了检测到的 IP 总是空的错误