divineomega/php-geolocation

PHP 库,用于确定 IP 地址所在的国

v2.0.1 2022-01-12 10:45 UTC

This package is auto-updated.

Last update: 2024-09-12 16:36:57 UTC


README

Build Status

本包提供 PHP 库,用于确定 IP 地址所在的国家。

安装

您可以使用 composer 轻松安装 PHP Geolocation。

composer require divineomega/php-geolocation

使用

PHP Geolocation 最简单的使用方法是创建一个新的 Locator 对象,并调用其 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(DivineOmega\Countries\Country)#4693 (16) {
  ["name"]=>
  string(13) "United States"
  ["officialName"]=>
  string(24) "United States of America"
  // etc...
}
*/

缓存

您可以将 PHP Geolocation 配置为使用任何 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 Geolocation 将尝试使用操作系统的原生 whois 命令来确定 IP 地址。如果您愿意,可以使用替代位置提供者。这可以通过使用 setLocationProvider 方法完成,如下所示。

$locator = new Locator;
$locator->setLocationProvider(new IpStack('my_ip_stack_api_key');

$country = $locator->getCountryByIP('93.184.216.34');

要获取免费 API 密钥,请在 Ip Stack 网站 上注册。

如果您希望开发自己的位置提供者,只需创建一个新的类,实现本包提供的 LocationProviderInterface。如果您在创建自己的位置提供者时需要帮助,可以查看现有的 WhoIsFreeGeoIP 位置提供者类。