Get IP Geolocation with PHP

There is no build in way or tool in PHP to get geographical location of an IP address. Thats why, we will need to use a third party api to get geographical location of an IP address.

There are many free and paid Geo apis are available today to get geolocation from an IP address. In this post I will use freegeoip.net api. It is very simple and easy. We do not need to register for api key and the most impotent thing is this api is absolutely free!

The ip2location Function

function ip2location($ip)
{
    # api url
    $api = 'http://freegeoip.net/json/' . $ip;

    # connect api with curl
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    $data = curl_exec($ch);
    curl_close($ch);

    # return reposed data
    return json_decode($data);
}

Usages

$geo = ip2location('8.8.8.8');
$geo->ip;
$geo->country_name;
$geo->region_name;
$geo->city;
$geo->zipcode;
$geo->areacode;

7 comments:

  1. Thanks for your script! It works great!

    ReplyDelete
  2. Great script, thanks!

    Just a small tip: you should declare your fonction as the following:
    function ip2location($ip = '')
    So that if we don't provide an IP, it will automatically use the client's IP.

    ReplyDelete
  3. You can also use :
    $geo->metro_code;
    $geo->latitude;
    $geo->longitude;

    ReplyDelete
  4. Thanks for your information. I have checked ip address location from this site WhoisXY.com . Here i got ip address location,country,etc..

    ReplyDelete
  5. That was actually really simple i'm used to working with the maxmind.com one this method & api is so much more lightweight.
    thanks for sharing the information

    ReplyDelete
  6. Hi, do you have a real example that could allow to copy past ? I know nothing but I would like to work on it :)
    Many thanks for your help.

    ReplyDelete

Go to top