我想检测用户的两个字母的大陆代码,以便我有条件地显示美国或更一般的电话号码。
E.g。如果大陆代码是北美或南美,请显示北美电话号码。否则,显示一般国际电话号码。
通过IP检测双字母大陆代码是否更容易,更轻量级?
答案 0 :(得分:2)
您可以使用MaxMind的官方API https://maxmind.github.io/GeoIP2-php/
代码示例
<?php
require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;
// This creates the Reader object, which should be reused across
// lookups.
$reader = new Reader('GeoLite2-Country.mmdb');
// Replace "city" with the appropriate method for your database, e.g.,
// "country".
$record = $reader->country('128.101.101.101');
echo ($record->continent->code);
答案 1 :(得分:1)
您可以使用此功能:
function get_continent_by_ip($ip = false) {
$code = false;
if (!$ip) {
$client = @$_SERVER['HTTP_CLIENT_IP'];
$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = @$_SERVER['REMOTE_ADDR'];
if (filter_var($client, FILTER_VALIDATE_IP)) {
$ip = $client;
} elseif (filter_var($forward, FILTER_VALIDATE_IP)) {
$ip = $forward;
} else {
$ip = $remote;
}
}
$response = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip={$ip}"));
if ($response && isset($response->geoplugin_continentCode)) {
$code = $response->geoplugin_continentCode;
}
return $code;
}
它检测用户的IP并返回大陆的代码