Previous Article Next Article PHP – How to Get Country, City, Longitude, Latitude Geolocation Information from Client IP Address.
Posted in API PHP & MySQL Server

PHP – How to Get Country, City, Longitude, Latitude Geolocation Information from Client IP Address.

PHP – How to Get Country, City, Longitude, Latitude Geolocation Information from Client IP Address. Posted on May 9, 2020Leave a comment
I'm Hari Prasad Chaudhary from Nepal, developer of the finest educational website/app "MeroSpark" and the finest eCommerce system "PasalaY". Here I share the code snippet which I learn during development.

Geo-location information of your traffic is very important to analyze the visitors. To get such information, either you need to install “IP database” in your server or access to API which provides such information. Previously I had written a tutorial to get client Country code with PHP, Python Flask and NodeJS using Cloudflare IP-Geolocation feature. Here I have mentioned a code by which you will get Country, city, and continent name from IP address.

PHP function to get Client IP:

function getclientip() {
    $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ipaddress = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ipaddress = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
       $ipaddress = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ipaddress = getenv('REMOTE_ADDR');
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
} 

PHP code to get IP Geo location information:

$ip = getclientip(); //use above function code.
$api = "https://www.iplocate.io/api/lookup/".urlencode($ip);
$idata = json_decode(file_get_contents($api));
$country = $idata->country;
$continent = $idata->continent;
$city = $idata->city;
print_r($idata);

Output JSON:

geolocation information

You can use this JSON data which is stored in $idata variable like $latitude = $idata->latitude;

I'm Hari Prasad Chaudhary from Nepal, developer of the finest educational website/app "MeroSpark" and the finest eCommerce system "PasalaY". Here I share the code snippet which I learn during development.

Leave a Reply

Your email address will not be published. Required fields are marked *