Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain location from ipinfo.io in PHP?

Tags:

json

php

api

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.

like image 590
Cody Raspien Avatar asked Jan 18 '15 16:01

Cody Raspien


2 Answers

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

like image 145
Octal Avatar answered Oct 06 '22 00:10

Octal


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.

like image 23
Jacek Kowalewski Avatar answered Oct 06 '22 00:10

Jacek Kowalewski