labor-digital / max-mind-helpers
基于MaxMind数据库实现IP到地理位置解析的帮助程序包
1.1.0
2020-04-28 20:23 UTC
Requires
- guzzlehttp/guzzle: ~6.0
- maxmind-db/reader: ^1.6.0
This package is auto-updated.
Last update: 2024-09-29 05:55:38 UTC
README
此库利用免费的MaxMind GeoLite2数据库执行IP => 地理位置查询。该包会将MaxMind库下载到您的本地文件系统,因此您可以确保客户端的IP永远不会离开您的服务器。
该包由两部分组成。第一部分是“下载器”,简化了获取数据库的过程,第二部分是“读取器”,它是MaxMind实现的外包装。读取器还可以使用PSR-16 SimpleCache\CacheInterface缓存查询以节省性能。
安装
使用Composer安装此包
composer require labor-digital/max-mind-helpers
用法
下载数据库
<?php use LaborDigital\MaxMindHelpers\Downloader; // This should probably run in a cron job once a day! $licenseKey = "YOUR LICENSE KEY"; $path = '/path/to/a/writable/directory/to/store/database'; $downloader = new Downloader($licenseKey, $path, new \GuzzleHttp\Client()); // This will check if an update is available based on the md5 hash of the local database // and download the (~40MB) file only if required $downloader->doDownloadIfRequired(); // Optional // Always triggers a download ignoring all requirements. $forceDownload = true; if($forceDownload) $downloader->download(); // Get path to library file $libraryFile = $downloader->getLibraryFile();
使用数据库
<?php use LaborDigital\MaxMindHelpers\Reader; // Define the path to the stored database $path = '/path/to/a/writable/directory/to/store/database/library.mmdb'; // Get the reader $reader = new Reader(new \MaxMind\Db\Reader($path)); // Optional // Use the PSR-16 Cache interface to cache queries for faster lookups $cache = new AwesomeCache(); // A class that implements \Psr\SimpleCache\CacheInterface $reader = new Reader(new \MaxMind\Db\Reader($path), $cache); // Get the geolocation of an ip $location = $reader->getLocation('129.200.121.12'); // Result ['latitude' => 0.0, 'longitude' => 0.0]; // Result if query failed: NULL // Get the geolocation of the current client's ip $location = $reader->getLocation(); // Result's as above. If you use this at 127.0.0.1 the result will always be NULL // Get additional information of an ip $info = $reader->getInformation('129.200.121.12');
进一步阅读
- https://github.com/maxmind/MaxMind-DB-Reader-php
- https://dev.maxmind.com/geoip/geoip2/geolite2/#IP_Geolocation_Usage
Postcardware
您可以自由使用此包,但如果它进入了您的生产环境,我们非常希望您能从您家乡给我们寄一张明信片,说明您正在使用我们哪个包。
我们的地址是:LABOR.digital - Fischtorplatz 21 - 55116 Mainz, Germany。
我们将在我们的公司网站上发布所有收到的明信片。