通过ip地址获取用户位置 - ipinfo.io

时间:2016-04-27 04:01:07

标签: php geolocation

我需要获取用户的当前位置并将其保存到数据库中。我有这个PHP的小片段和来自ipinfo.io的Js

但PHP代码不起作用,js版本可以。

$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
echo $details->city; // -> outputs nothing


<script>
    $.get("http://ipinfo.io", function(response) {
   console.log(response.city);//logged my current city
    }, "jsonp");
</script>

知道如何实现PHP版本吗?

更新

我试过

  var_dump($details)

告诉我

  object(stdClass)[1]
  public 'ip' => string '::1' (length=3)
  public 'hostname' => string 'localhost' (length=9)
  public 'city' => null
  public 'country' => string 'AU' (length=2)
  public 'loc' => string '-27.0000,133.0000' (length=17)

我在localhost测试它,我的国家是菲律宾

1 个答案:

答案 0 :(得分:0)

你不会把你的城市和你的国家带到&#34; localhost&#34;从这个网址,我不会想到。你可以在localhost之外的服务器上测试吗?我发现当我在localhost上测试时,我得到了相同数量的字段,我得到了#34; null&#34;在&#39; city&#39;和&#34; AU&#34;在&#39; country&#39;像你一样。但当我把它移到托管的测试服务器上时,我得到了这个(我已经编辑了我的&#39;真实的数据):

object(stdClass)#1(8){[&#34; ip&#34;] =&gt; string(10)&#34; 99.99.99.99&#34; [&#34;主机名&#34;] =&GT; string(35)&#34; 99-99-99-99.dhcp.leds.tx.charter.com&#34; [&#34;城市&#34;] =&GT;字符串(10)&#34;我的城市&#34; [&#34;区域&#34;] =&GT;字符串(7)&#34;我的国家&#34; [&#34;国家&#34;] =&GT; string(2)&#34; US&#34; [&#34; LOC&#34;] =&GT; string(16)&#34; 99.9999,-99.9999&#34; [&#34;组织&#34;] =&GT; string(30)&#34; Blah Blah Blah Communications&#34; [&#34;邮政&#34;] =&GT; string(5)&#34; 99999&#34; }。

所以你注意到它也应该返回&#34; region&#34;,&#34; org&#34;,&#34; postal&#34;,它在我托管的测试平台上运行。在&#34; localhost&#34;,它将这些字段完全从返回的内容中删除(我做了一个var_dump,但他们并没有)。如果您已打开E_NOTICE,那么您将在日志文件中看到如果您正在使用它们而未返回的字段中的警告(我是)。 希望这会有所帮助。