Getting the location from an IP address

If you want to retrieve information like the city, state, and country of a visitor from their IP address, so that you can customize your web page according to their location.  There a good and reliable way to do this in PHP. You are using JavaScript for client-side scripting, PHP for server-side scripting, and MySQL for the database.

You could download a free GeoIP database and lookup the IP address locally, or you could use a third party service and perform a remote lookup. This is the simpler option, as it requires no setup, but it does introduce additional latency.

$ curl ipinfo.io/8.8.8.8
{
  "ip": "8.8.8.8",
  "hostname": "google-public-dns-a.google.com",
  "loc": "37.385999999999996,-122.0838",
  "org": "AS15169 Google Inc.",
  "city": "Mountain View",
  "region": "CA",
  "country": "US",
  "phone": 650
}

Here’s a PHP example:

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

You can also use it client-side. Here’s a simple jQuery example:

$.get("http://ipinfo.io", function(response) {
    console.log(response.city);
}, "jsonp");

 

Leave a Reply

Your email address will not be published. Required fields are marked *