1

I need to get user's current location and save it to the database. I have this small snippet in PHP and Js from ipinfo.io

But PHP code does not work, the js version does.

$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
echo $details->city; // -> outputs nothing


<script>
    $.get("http://ipinfo.io", function(response) {
   console.log(response.city);//logged my current city
    }, "jsonp");
</script>

Any idea how to achieve the PHP version?

update

I tried

  var_dump($details)

Shows me

  object(stdClass)[1]
  public 'ip' => string '::1' (length=3)
  public 'hostname' => string 'localhost' (length=9)
  public 'city' => null
  public 'country' => string 'AU' (length=2)
  public 'loc' => string '-27.0000,133.0000' (length=17)

I am testing it in localhost and my country is Philippines

Danielle Rose Mabunga
  • 1,676
  • 4
  • 25
  • 48

1 Answers1

0

You're not going to get your city and your country on "localhost" from this url, I don't think. Can you test it on a server besides localhost? I found that when I tested on localhost I got the same number of fields you did, and I got "null" in 'city' and "AU" in 'country' like you did. But when I moved it up to a hosted test server, I got this (I've edit my 'real' data):

object(stdClass)#1 (8) { ["ip"]=> string(10) "99.99.99.99" ["hostname"]=> string(35) "99-99-99-99.dhcp.leds.tx.charter.com" ["city"]=> string(10) "My City" ["region"]=> string(7) "My State" ["country"]=> string(2) "US" ["loc"]=> string(16) "99.9999,-99.9999" ["org"]=> string(30) "Blah Blah Blah Communications" ["postal"]=> string(5) "99999" } .

So you notice that it is supposed to also return "region", "org", and "postal", which it DOES on my hosted test platform. On "localhost",it leaves those fields completely out of the contents returned (I did a var_dump and they weren't there). If you have E_NOTICE turned on, you'll see warnings in your log file for the fields that aren't returned IF you are using them (and I am). Hope this helps.

McAuley
  • 413
  • 1
  • 3
  • 13