如何获取在PHP从ipinfo.io的位置? [英] How to obtain location from ipinfo.io in PHP?
本文介绍了如何获取在PHP从ipinfo.io的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 ipinfo.io 让我当前使用PHP市(位置)。
不过,我无法看到使用这块code的时候,我的城市。
$ ip地址= $ _ SERVER [REMOTE_ADDR];功能ip_details($ IP){
$ JSON =的file_get_contents(http://ipinfo.io/{$ip}/geo);
$细节= json_de code($ JSON);
返回$细节;
}$细节= ip_details($ ip地址);
回声$详情 - >城市;
我不知道哪里出错。
解决方案
函数getClientIP(){
如果(!空($ _ SERVER ['HTTP_CLIENT_IP'])){
$ IP = $ _ SERVER ['HTTP_CLIENT_IP'];
} ELSEIF(!空($ _ SERVER ['HTTP_X_FORWARDED_FOR'])){
$ IP = $ _ SERVER ['HTTP_X_FORWARDED_FOR'];
}其他{
$ IP = $ _ SERVER ['REMOTE_ADDR'];
}
返回$ IP;
}$ IPADDRESS = getClientIP();功能ip_details($ IP){
$ JSON =的file_get_contents(http://ipinfo.io/{$ip}/geo);
$细节= json_de code($ JSON,真正的);
返回$细节;
}$细节= ip_details($ ip地址);
回声$细节['城市'];
这应该工作。
不过,我建议你要习惯使用卷曲,而不是file_get_contents()函数,如果你想有一个在线资源。 http://stackoverflow.com/a/5522668/3160141
I am using ipinfo.io to get my current city (location) using PHP.
However, I am not able to see my city when using this piece of code.
$ipaddress = $_SERVER["REMOTE_ADDR"];
function ip_details($ip) {
$json = file_get_contents("http://ipinfo.io/{$ip}/geo");
$details = json_decode($json);
return $details;
}
$details = ip_details($ipaddress);
echo $details->city;
I don't know where the error is.
解决方案
function getClientIP(){
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
$ipaddress = getClientIP();
function ip_details($ip) {
$json = file_get_contents("http://ipinfo.io/{$ip}/geo");
$details = json_decode($json, true);
return $details;
}
$details = ip_details($ipaddress);
echo $details['city'];
this should work.
however, I recommend you to get used to use curl instead of file_get_contents(), if you want a online resource. http://stackoverflow.com/a/5522668/3160141
这篇关于如何获取在PHP从ipinfo.io的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文