【问题标题】:Get user location by ip address - ipinfo.io通过 ip 地址获取用户位置 - ipinfo.io
【发布时间】:2016-08-21 04:10:58
【问题描述】:

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

但是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 测试它,我的国家是菲律宾

【问题讨论】:

标签: php geolocation


【解决方案1】:

我不认为,您不会从该网址将您的城市和您的国家/地区放在“本地主机”上。您可以在 localhost 以外的服务器上对其进行测试吗?我发现当我在 localhost 上进行测试时,我得到的字段数量与你一样,并且我在“城市”中得到“null”,在“国家”中得到“AU”,就像你一样。但是当我将它移到托管测试服务器时,我得到了这个(我已经编辑了我的“真实”数据):

object(stdClass)#1 (8) { ["ip"]=> string(10) "99.99.99.99" ["hostname"]=> string(35) "99-99-99-99.dhcp .leds.tx.charter.com" ["city"]=> string(10) "My City" ["region"]=> string(7) "My State" ["country"]=> string(2) "US" ["loc"]=> string(16) "99.9999,-99.9999" ["org"]=> string(30) "Blah Blah Blah Communications" ["postal"]=> string(5) "99999 " } .

因此,您注意到它还应该返回“region”、“org”和“postal”,这在我的托管测试平台上是这样做的。在“localhost”上,它将这些字段完全排除在返回的内容之外(我做了一个 var_dump,但它们不存在)。如果你打开了 E_NOTICE,你会在你的日志文件中看到警告,如果你正在使用它们(我是)没有返回的字段。 希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2018-03-30
    • 2012-06-15
    • 1970-01-01
    • 2020-06-10
    • 2019-02-10
    • 2014-02-13
    • 2018-06-22
    相关资源
    最近更新 更多