PHP:使用API​​的真实IP地址

时间:2017-03-21 20:07:17

标签: javascript php json

你好我使用这个api:http://ipapi.co/json来获取localhost(127.0.0.1)中的国家,城市和真实IP地址工作完美,但是当我把我的代码放到我的网站时我的代码不显示客户端的地址,但服务器的地址我该如何解决这个问题?

我可以使用$_SERVER['REMOTE_ADDR'];获取客户端IP地址,但我需要此api才能获得国家和城市:http://ipapi.co/json

Function TTT() {
    $ip = false;
    $city = false;
    $region = false;
    $country = false;
    $country_code = false;

    if($json = @file_get_contents("http://www.geoplugin.net/json.gp")) {
      $obj = json_decode($json);
      if(isset($obj->geoplugin_request) && $obj->geoplugin_request != false) {
        $ip = "IP: ". $obj->geoplugin_request. "</br>";
      }
      if(isset($obj->geoplugin_city) && $obj->geoplugin_city != false) {
        $city = "City: ". $obj->geoplugin_city. "</br>";
      }
      if(isset($obj->geoplugin_city) && $obj->geoplugin_city != false) {
        $region = "Region: ". $obj->geoplugin_city. "</br>";
      }
      if(isset($obj->geoplugin_countryName) && $obj->geoplugin_countryName != false) {
        $country = "Country: ". $obj->geoplugin_countryName. "</br>";
      }
      if(isset($obj->geoplugin_countryCode) && $obj->geoplugin_countryCode != false) {
        $country_code = "Country Code: ". $obj->geoplugin_countryCode. "</br>";
      }

      return $ip. $city. $region. $country. $country_code;
    }
}

echo TTT();

2 个答案:

答案 0 :(得分:3)

http://ipapi.co/json

使用api

$obj = json_decode($json);

将此JSON放在关联数组中:

{
    "ip": "00.00.00.00",
    "city": "Atlanta",
    "region": "Georgia",
    "country": "US",
    "postal": "31532",
    "latitude": 34.461,
    "longitude": -85.9877,
    "timezone": "America/New_York"
}

访问城市和地区像这样:

if(isset($obj->city) && $obj->city != false) {
    $city = "City: ". $obj->city. "</br>";
  }
if(isset($obj->region) && $obj->region != false) {
    $region = "Region: ". $obj->region. "</br>";
  }

您似乎没有使用原先声明使用的API。

答案 1 :(得分:2)

您必须在对远程服务的请求中包含访问者的IP。根据我的测试,您可以将客户端IP地址放在URL中,如下所示:

function TTT() {
    $ip = false;
    $city = false;
    $region = false;
    $country = false;
    $country_code = false;

    if($json = @file_get_contents("http://ipapi.co/" . $_SERVER['REMOTE_ADDR'] . "/json")) {
      $obj = json_decode($json);
      if(isset($obj->ip) && $obj->ip != false) {
        $ip = "IP: ". $obj->ip. "</br>";
      }
      if(isset($obj->city) && $obj->city != false) {
        $city = "City: ". $obj->city. "</br>";
      }
      if(isset($obj->region) && $obj->region != false) {
        $region = "Region: ". $obj->region. "</br>";
      }
      if(isset($obj->country) && $obj->country != false) {
        $country = "Country: ". $obj->country. "</br>";
      }

      return $ip. $city. $region. $country;
    }
}

echo TTT();

注意:该API的响应如下:

{
  "ip": "8.8.8.8",
  "city": "Mountain View",
  "region": "California",
  "country": "US",
  "postal": "94035",
  "latitude": 37.386,
  "longitude": -122.0838,
  "timezone": "America/Los_Angeles"
}