Get geolocation from ip in PHP

In PHP, there is no direct way to get geolocation of an IP address. Therefore we have to use third party API to get geolocation from ip address.

There are many paid and free APIs available to get geolocation from ip address. I found a very simple and easy api It is a public RESTful web service API for searching geolocation of IP addresses and host names. API usage is limited to 10,000 queries per hour and it is absolutely free. Most important we don’t need to register for api key to use this API.


The API supports both HTTP and HTTPS. It provides the result in csv, xml and json formats.

Function IP2Geolocation

function ip2geolocation($ip)
    # api url
    $apiurl = '' . $ip;

    # api with curl
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $apiurl);
    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 data
    return json_decode($data);

Now just pass your IP address to this function to get geolocation as below:

$geolocation = ip2geolocation('');

I hope this post will help you to get geolocation from IP address.


Get geolocation from ip address
get geolocation from ip address