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 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 = '' . $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);

    # return reposed data
    return json_decode($data);


$geo = ip2location('');


  1. Thanks for your script! It works great!

  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.

  3. You can also use :

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

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

  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.


Go to top