如何在 PHP 中从 ipinfo.io 获取位置? [英] How to obtain location from ipinfo.io in PHP?

查看:115
本文介绍了如何在 PHP 中从 ipinfo.io 获取位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

我不知道错误在哪里.

推荐答案

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

however, I recommend you to get used to use curl instead of file_get_contents(), if you want a online resource. https://stackoverflow.com/a/5522668/3160141

这篇关于如何在 PHP 中从 ipinfo.io 获取位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆