PHP - 检测国家/地区

Mic*_*ius 0 php country country-codes geo

可能重复:
用于在php中检测用户contry的包?
基于IP地址的地理位置 - PHP

我想检测我访客的国家.

我在谷歌找到了解决方案,但结果却一无所获.

你能帮助我吗?

Dan*_*iel 6

这是我通过访问者的ip获取国家的方式.

// this is where you get the ip
$ip = $_SERVER['REMOTE_ADDR'];

// this is where you include the code that gets the country
// you can find the code for this file on the link below    
include("geoiploc.php");

// this is where you create the variable that get you the name of the country
$country = getCountryFromIP($ip, " NamE ");
Run Code Online (Sandbox Code Playgroud)

php geo ip loc不起作用

希望这可以帮助.

愿代码与你同在!

更新:

这是我一直在使用的另一种方法

    $json = file_get_contents('http://ipinfo.io/' . $this->getIP());
    $data = json_decode($json);
    return $data->country;
Run Code Online (Sandbox Code Playgroud)

还有这项服务,但我发现上面的那个更好......

    'http://getcitydetails.geobytes.com/GetCityDetails?fqcn=' . $this->getIP()
Run Code Online (Sandbox Code Playgroud)

这是获取ip的好方法:

private function getIP() {
    $server_keys = [
        'HTTP_CLIENT_IP',
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_FORWARDED',
        'HTTP_X_CLUSTER_CLIENT_IP',
        'HTTP_FORWARDED_FOR',
        'HTTP_FORWARDED',
        'REMOTE_ADDR'
    ];

    foreach ($server_keys as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
                if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
                    return $ip;
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

希望它可以帮到某人!