danielme85/laravel-geoip2

Maxminds PHP API GeoIP2 的服务提供者和数据库下载器。

安装次数: 96,433

依赖者: 0

建议者: 0

安全: 0

星标: 13

关注者: 3

分支: 3

开放问题: 0

类型:laravel

v1.2.0 2020-09-10 20:20 UTC

This package is auto-updated.

Last update: 2024-08-29 04:36:59 UTC


README

Laravel 5+ 版本的服务提供者和数据库下载器,用于 Maxminds PHP API GeoIP2。 https://github.com/maxmind/GeoIP2-php

License: MIT Build Status

截至2020年1月,您现在需要在 MaxMind 创建一个账户并获取一个 "许可密钥"。目前仍然是免费的。

https://dev.maxmind.com/geoip/geoip2/geolite2/

安装

在 composer.json 中

"require": {
        "danielme85/laravel-geoip2": "dev-master",
        ....
}

或者命令:composer require danielme85/laravel-geoip2

将您的 geoip 许可证添加到您的 env 文件中

GEOIP2_LICENSE=XXXXX

Laravel 5.x

在 config/app.php 下的服务提供者中添加
(如果您使用 Laravel 5.5+,则可以跳过此步骤,因为已为该包启用自动发现。)

//Service Providers
danielme85\Geoip2\Geoip2ServiceProvider::class,
//Facades
'Reader'  => danielme85\Geoip2\Facade\Reader::class,

Lumen 5.x

添加到您的 bootstrap/app.php 文件中

$app->register(danielme85\Geoip2\Geoip2ServiceProvider::class);
...
$app->configure('app'); 
...
class_alias('danielme85\Geoip2\Facade\Reader, 'Reader');
$app->withFacades();

配置

将配置文件发布到您的 Laravel 项目中

php artisan vendor:publish --provider="danielme85\Geoip2\Geoip2ServiceProvider"

以下默认设置将立即生效

return [
    'geoip2' => [
        'downloadUrl' => 'http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz', //url db file download
        'tempFile' => 'app/GeoLite2-City.mmdb.gz', //temp download file name
        'dbName' => 'app/GeoLite2-City.mmdb', //Geoip DB filename
        'localhost' => '8.8.8.8' //when running on localhost (or for general testing) you can specify a fake ip address here.
    ]
];

使用方法

您需要首先下载 Maxmind Geoip,默认配置为城市版本(约 30MB 下载,50MB 解压)。

php artisan geoip:download

下载了数据库文件后,您就可以获取一些位置数据了

use danielme85\Geoip2\Facade\Reader;
...
$reader = Reader::connect();
$result = $reader->city($ip);

一旦有了 Reader:connect 对象,使用方法与 maxminds 文档 https://github.com/maxmind/GeoIP2-php 相同。

示例用法,基于 IPv4 地址返回 JSON 位置数据。

<?php
use danielme85\Geoip2\Facade\Reader;
...

function getLocation(Request $request) {
   $reader = Reader::connect();
   /*
   I was experiencing inaccurate results... until I remembered that my web server traffic was routed trough CloudFlare :p
   In that case CloudFlare provides the original client ip in the following header information.
   */   
   if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
       $ip = $_SERVER["HTTP_CF_CONNECTING_IP"];
   }
   else {
       $ip = $request->ip();
   }
   //the city() function from the GeoIp2 Php API will throw an exception if the ip-address is not found in the DB.
   try {
       $geodata = $reader->city($ip)->jsonSerialize(); //jsonSerialize seems to actually return an associative array.
   }
   catch (\Exception $e) {
       Log::warning($e->getMessage());
       return response()->json("Geo-location not found!", 500);
   }

   return response()->json($geodata);
}

此产品包含 MaxMind 创建的 GeoLite2 数据,可在 http://www.maxmind.com 获取