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位置提供商類。