我正在使用ipinfo.io来获取我当前的城市(位置)。
然而,当我使用这段代码时,我无法看到我所在的城市。
$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;
我不知道错误在哪里。
发布于 2015-01-19 00:47:24
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'];
这应该是可行的。
但是,如果您需要在线资源,我建议您习惯使用curl而不是file_get_contents()。https://stackoverflow.com/a/5522668/3160141
发布于 2015-01-19 00:32:58
你在使用localhost吗?尝试以下代码:
$ipaddress = $_SERVER["REMOTE_ADDR"];
function ip_details($ip) {
$json = file_get_contents("http://ipinfo.io/{$ip}/geo");
$details = json_decode($json); // HERE!!!
return $details;
}
$details = ip_details($ipaddress);
echo $details->ip; // CHANGE TO IP!!!
如果它返回您的IP,则一切正常,您的IP可能是127.0.0.1
,而此站点不知道位置,因此未设置$details->city
。如果城市不在那里,您必须检查if (isset($details->city))
并创建一个替代脚本。
我看你还是有问题。试着这样做:
$string = file_get_contents('http://ipinfo.io/8.8.8.8/geo');
var_dump($string);
$ipaddress = $_SERVER["REMOTE_ADDR"];
var_dump($ipaddress);
$string2 = file_get_contents('http://ipinfo.io/'.$ipaddress.'/geo');
var_dump($string2);
并在失败的评论中写下;)。
如果只有IP部分正常,请尝试阅读以下内容: File_get_contents not working?
并以最大限度的错误报告运行此代码:
error_reporting(-1);
在这部分代码之前。
发布于 2020-01-08 10:19:21
我知道这篇文章很老了,但是对于正在寻找相同问题的人来说,如果它是在Localhost上,这将解决问题:
$ipaddress = $_SERVER["SERVER_ADDR"];
function ip_details($ip) {
$json = file_get_contents("http://ipinfo.io/");
$details = json_decode($json); // decode json with geolocalization information
return $details;
}
$details = ip_details($ipaddress);
echo $details->ip; // Use city, ip or other thing... see https://ipinfo.io
如果它仅在Web服务器上,请使用以下命令:
$server = $_SERVER['REMOTE_ADDR']; //in localhost this is ::1
echo "Your IP is: ".$server;
注:2个代码获取公网ip,1个代码获取本地主机的公网ip,2个代码获取web服务器的公网ip。:)
https://stackoverflow.com/questions/28012011
复制相似问题