Snippet. PHP. Geolocation Using the FreeGeoIp Webservice

Freegeoip.net is a free webservice, which geolocation searching of IP addresses. The following PHP snippet shows how to get the geolocation service based on an IP address.

function freegeoip_locate($ip) {
    $url = "http://freegeoip.net/json/".$ip;
    $geo = json_decode(file_get_contents($url), true);
    return $geo;
}

The returned information will be an array wit the following keys: city, region_code, region_name, metrocode, zipcode, longitude, country_name, country_code, ip, latitude. Here is an example how to use it:

$geo = freegeoip_locate($_SERVER['REMOTE_ADDR']);

echo "Country: " . $geo['country_name'];

Updated on: 19 Apr 2024