PHP - 检测国家/地区

时间:2013-01-19 13:07:16

标签: php geo country country-codes

  

可能重复:
  package for detecting users contry in php?
  Geo Location based on IP Address - PHP

我想检测访问者的国家。

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

你能帮助我吗?

2 个答案:

答案 0 :(得分: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 ");

php geo ip loc does not work

希望这有帮助。

代码可以和你在一起!

更新

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

    $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;
                }
            }
        }
    }
}

希望它有所帮助!

答案 1 :(得分:1)

    <?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); 

?>

Demo Link