通过IP检测两个字母的大陆代码


Detect two-letter continent code by IP

上下文:

我想检测我的用户的两个字母的大陆代码,以允许我有条件地显示美国或更通用的电话号码。

例如,如果大陆代码为北美或南美,则显示北美电话号码。否则,显示通用国际电话号码

我尝试过的:

  1. 使用轻量级函数解决了Stack Overflow上的类似问题,但在我的情况下,该函数没有输出任何内容(即空白)
  2. PHP手册列出了geoip扩展的geoap_content_code_by_name函数,但安装这个扩展似乎有些过头了,此外,我对WHM/cPanel的命令行安装一点也不熟悉

我的问题:

有没有一种更简单、重量更轻的方法可以通过IP检测两个字母的大陆代码?

您可以使用MaxMind的官方APIhttps://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);

您可以使用此函数:

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并返回大陆的代码