Getting the location from an IP address [closed] Getting the location from an IP address [closed] php php

Getting the location from an IP address [closed]


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.

One third party service you could use is mine, http://ipinfo.io. They provide hostname, geolocation, network owner and additional information, eg:

$ 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("https://ipinfo.io/json", function (response) {    $("#ip").html("IP: " + response.ip);    $("#address").html("Location: " + response.city + ", " + response.region);    $("#details").html(JSON.stringify(response, null, 4));}, "jsonp");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><h3>Client side IP geolocation using <a href="http://ipinfo.io">ipinfo.io</a></h3><hr/><div id="ip"></div><div id="address"></div><hr/>Full response: <pre id="details"></pre>