PHP - 检测国家
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14414705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP - Detect country
提问by Michael Antonius
Possible Duplicate:
package for detecting users contry in php?
Geo Location based on IP Address - PHP
I want to detect my visitor's country.
我想检测我的访客所在的国家/地区。
And I have found the solution at Google, but the result is nothing.
我在谷歌找到了解决方案,但结果什么都没有。
Can you help me?
你能帮助我吗?
回答by Daniel
Here is my way of getting the country along with the ip of the person visiting.
这是我通过访问者的 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 ");
Hope this helps.
希望这可以帮助。
May the code be with you!
愿代码与你同在!
Update:
更新:
Here is another method I've been using
这是我一直在使用的另一种方法
$json = file_get_contents('http://ipinfo.io/' . $this->getIP());
$data = json_decode($json);
return $data->country;
There is also this service, but I found the one above much better...
也有这项服务,但我发现上面的要好得多...
'http://getcitydetails.geobytes.com/GetCityDetails?fqcn=' . $this->getIP()
Here is a good way to get the ip:
这是获取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;
}
}
}
}
}
Hope it helps someone!
希望它可以帮助某人!
回答by Kelley Lewis
<?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);
?>

