php geolocation
v2.0.1
该软件包提供了一个PHP库来确定IP地址的国家。
您可以轻松地使用作曲家安装PHP地理位置。
composer require divineomega/php-geolocation
PHP地理位置的最简单用法是创建一个新的定位器对象并调用其getCountryByIP方法。
// Get country of the current request's IP address
$ country = ( new Locator )-> getCountryByIP ( $ _SERVER [ ' REMOTE_ADDR ' ]);
// Get country of a specific IP address
$ country = ( new Locator )-> getCountryByIP ( ' 93.184.216.34 ' );
// Returns a Country object
/*
object(DivineOmegaCountriesCountry)#4693 (16) {
["name"]=>
string(13) "United States"
["officialName"]=>
string(24) "United States of America"
// etc...
}
*/您可以配置PHP地理位置以使用任何符合PSR-6的缓存库。使用setCache方法很容易完成。
以下示例配置文件缓存(由cache/filesystem-adapter软件包提供)。
use League Flysystem Adapter Local ;
use League Flysystem Filesystem ;
use Cache Adapter Filesystem FilesystemCachePool ;
$ filesystemAdapter = new Local ( __DIR__ . ' / ' );
$ filesystem = new Filesystem ( $ filesystemAdapter );
$ cachePool = new FilesystemCachePool ( $ filesystem );
$ locator = new Locator ;
$ locator -> setCache ( $ cachePool );
$ country = $ locator -> getCountryByIP ( ' 93.184.216.34 ' );默认情况下,PHP地理位置将尝试使用操作系统的本机whois命令来确定IP地址。如果您希望可以使用替代位置提供商。可以使用setLocationProvider方法进行,如下所示。
$ locator = new Locator ;
$ locator -> setLocationProvider ( new IpStack ( ' my_ip_stack_api_key ' );
$ country = $ locator -> getCountryByIP ( ' 93.184.216.34 ' );要在IP Stack的网站上获得免费的API密钥注册。
如果您想开发自己的位置提供商,只需创建一个新的类,以实现本软件包中提供的LocationProviderInterface 。如果您需要帮助创建自己的位置提供商,请参阅现有的WhoIs和FreeGeoIP位置提供商类。