Detect The Country Of The Visitor In PHP

By Faruque Ahamed Mollick

In web development projects, it may be required to detect the country of the visitor to perform some condition depending upon the country of the visitor. So in this post, we are going to see in PHP how we can get the country of the visitor who is visiting our website.

Get visitors country and city in PHP using freegeoip API

To detect the country of the visitor, we are going to use the IPInfoDB API. IPInfoDB API will provide us various details about the like visitor’s country, city, latitude, longitude and more just from the IP address. So we also have to get the IP address of the visitor.

Now below is the PHP code of the function that will return the country of the visitor:

<?php
function visitor_country($ipinfodb_api,$ip_address)
{
// Retrive visitor's JSON data from IP address
$ipinfodb_json = file_get_contents("http://api.ipinfodb.com/v3/ip-city/?format=json&key=".$ipinfodb_api."&ip=".$ip_address."");
// Convert the JSON data into array
$ipinfodb_arr = json_decode($ipinfodb_json);
// Get the country from the array
$country_name = $ipinfodb_arr->countryName;
return $country_name;
}
?>

You can easily display the country of the visitor using the function that we have just created. We just need to pass our IPInfoDB API key as the parameter to the function we created to get the country of the visitor. So we have to get the IP address of the visitor also.

Below is another function to get the IP address of the visitor:



<?php
// Get the IP address
 function visitor_ip_address(){
    
    $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;
 }

 

After that, we can get the country of the visitor. Below is the code that will display the country name of the visitor:

<?php
// Get visitor's country
echo visitor_country("PUT_YOUR_IPINFODB_API_KEY",visitor_ip_address());
?>

The above code will display the country of the visitor.

That’s it. We have successfully able to detect the country of the visitor.

Get random word from English dictionary in PHP tutorial

Leave a Reply

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