通过API查询ip时出现问题php

problem when consulting ip through API php

我使用的是http://ipinfo.io的服务,我使用下面的代码通过我的IP查询我所在位置的信息,但是在localhost中它可以正常工作但是在生产服务器中没有,而不是扔我来自用户的 ip,它 returns 进行查询的服务器的 IP。

我希望它检测访问者的 ip,而不是发出请求的 ip

class ipController{
  private $token="XXXXXX";


public function __construct(){

        $handle = curl_init();
        $url = "http://ipinfo.io?token=".$this->token;

        // Set the url
        curl_setopt($handle, CURLOPT_URL, $url);
        // Set the result output to be a string.
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($handle);
         //var_dump($output);  
        curl_close($handle);
        $datos = json_decode($output);
        var_dump($datos); 

        //Se setean las propiedades
        $this->ip = $datos->ip;
        $this->hostname = $datos->hostname;
        $this->city = $datos->city;
        $this->region = $datos->region;
        $this->country = $datos->country;
        $this->loc = $datos->loc;
        $this->postal = $datos->postal;
        $this->org = $datos->org;
}
}

根据文档,您需要将 ip 地址放在端点中。只是令牌给你自己的 ip 地址,这是服务器

https://ipinfo.io/developers#ip-address-parameter

ipinfo.io/$visitors_ip?token=$TOKEN

我假设它是 php 向 ipinfo 发出请求,因此您获取服务器详细信息的原因

You were getting the server IP address because you were sending your request with curl and when using the curl, the sever does the request with its own IP.

为了获得访问者的 IP 地址,您必须使用 $_SERVER['REMOTE_ADDR']$_SERVER['REMOTE_HOST'] 变量,但这有时 return 并不是访问者的正确 IP 地址,所以你可以使用下面的函数来获取用户的正确IP

function get_ip_address() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
    $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
    $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
    $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
    $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
    $ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
    $ipaddress = $_SERVER['REMOTE_ADDR'];
else
    $ipaddress = 'UNKNOWN';
return $ipaddress;
}

然后就可以通过url这样获取ip信息了

$ip = get_ip_address();
$url = "http://ipinfo.io/$ip?token=$token";

//you can the get the data with
$data = url_get_contents($url);

//curl function to send your request
function url_get_contents($Url) {
  if (!function_exists('curl_init')){ 
      die('CURL is not installed!');
  }
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $Url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $output = curl_exec($ch);
  curl_close($ch);
  return $output;
}