首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在PHP中从ipinfo.io中获取位置?

如何在PHP中从ipinfo.io中获取位置?
EN

Stack Overflow用户
提问于 2015-01-19 00:27:04
回答 3查看 16.1K关注 0票数 6

我正在使用ipinfo.io来获取我当前的城市(位置)。

然而,当我使用这段代码时,我无法看到我所在的城市。

代码语言:javascript
运行
复制
$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;

我不知道错误在哪里。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-01-19 00:47:24

代码语言:javascript
运行
复制
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

票数 5
EN

Stack Overflow用户

发布于 2015-01-19 00:32:58

你在使用localhost吗?尝试以下代码:

代码语言:javascript
运行
复制
$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))并创建一个替代脚本。

我看你还是有问题。试着这样做:

代码语言:javascript
运行
复制
$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?

并以最大限度的错误报告运行此代码:

代码语言:javascript
运行
复制
error_reporting(-1);

在这部分代码之前。

票数 2
EN

Stack Overflow用户

发布于 2020-01-08 10:19:21

我知道这篇文章很老了,但是对于正在寻找相同问题的人来说,如果它是在Localhost上,这将解决问题:

代码语言:javascript
运行
复制
$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服务器上,请使用以下命令:

代码语言:javascript
运行
复制
$server = $_SERVER['REMOTE_ADDR']; //in localhost this is ::1
echo "Your IP is: ".$server;

注:2个代码获取公网ip,1个代码获取本地主机的公网ip,2个代码获取web服务器的公网ip。:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28012011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档