Cody Raspien Cody Raspien - 4 months ago 64
PHP Question

How to obtain location from ipinfo.io in 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;


I don't know where the error is.

Answer
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. http://stackoverflow.com/a/5522668/3160141