How to obtain location from ipinfo.io in PHP?

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'];

this should work.

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


Are you working on localhost? Try the following code:

$ipaddress = $_SERVER["REMOTE_ADDR"];

function ip_details($ip) {
    $json = file_get_contents("http://ipinfo.io/{$ip}/geo");
    $details = json_decode($json); // HERE!!!
    return $details;
}

$details = ip_details($ipaddress);
echo $details->ip; // CHANGE TO IP!!!

If it returns Your IP, everything is OK, Your IP is probably 127.0.0.1, and this site does not know the location, so $details->city is not set. You must check if (isset($details->city)) and make an alternative script if the city is not there.


I see You still got problems. Try to do something like this:

$string = file_get_contents('http://ipinfo.io/8.8.8.8/geo');
var_dump($string);
$ipaddress = $_SERVER["REMOTE_ADDR"];
var_dump($ipaddress); 
$string2 = file_get_contents('http://ipinfo.io/'.$ipaddress.'/geo');
var_dump($string2);

And write in comments which one failed ;).


If only IP part is OK, try to read this one: File_get_contents not working?

And also run this code with maximum error reporting:

error_reporting(-1);

Before this part of code.

Tags:

Php

Json

Api