PHP - 检测国家/地区[重复]

问题描述 投票:0回答:2

我想检测我的访客所在的国家/地区。

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

你能帮我吗?

php geo country country-codes
2个回答
7
投票

这是我获取国家/地区以及访问者 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 ");

php geo ip loc 不起作用

希望这有帮助。

愿代码与你同在!

更新:

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

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

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

    'http://getcitydetails.geobytes.com/GetCityDetails?fqcn=' . $this->getIP()

这里有一个获取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;
                }
            }
        }
    }
}

希望它对某人有帮助!


2
投票
    <?php 
// Author: www.easyjquery.com 
$ip = $_SERVER['REMOTE_ADDR']; 
// remember chmod 0777 for folder 'cache' 
$file = "./cache/".$ip; 
if(!file_exists($file)) { 
    // request 
    $json = file_get_contents("http://api.easyjquery.com/ips/?ip=".$ip."&full=true"); 
    $f = fopen($file,"w+"); 
    fwrite($f,$json); 
    fclose($f); 
} else { 
    $json = file_get_contents($file); 
} 

$json = json_decode($json,true); 
echo "<pre>"; 
print_r($json); 

?>

演示链接

© www.soinside.com 2019 - 2024. All rights reserved.