How To Find Visitor's Country

When developing multilingual web applications, it is necessary to determine the geographic location of the users in order to present content that is relevant to that place. Some websites even modify country flags and themes to reflect this.

You may easily obtain the visitor's IP address using PHP, but there is no method to obtain the visitor's country information from it. As a result, you must rely on external online services to give location information. I'll show you how to use the GeoPlugin API and PHP to determine the country of visitors.

Getting the Country Name from an IP Address

GeoPlugin is a free web service that provides the geographical location of site visitors based on their IP address. It provides a variety of services such as PHP, JSON, and so on, and in this tutorial, I'll utilise the JSON API to find the nation name.

You must use this URL to access the service.

http://www.geoplugin.net/json.gp?ip=IP_ADDRESS

The API will return the name of the country as well as other location-related information such as city, currency, latitude, longitude, and so on.

I've written a PHP function called GetUserIP() below. It takes an IP address as an argument, connects with the geoPlugin API, and returns the country name for that IP address.

If you're using WordPress, copy and paste the code below into your theme's functions.php file.

function GetUserIP($IP) {
    if(isset($IP)) {
        $details = file_get_contents('http://www.geoplugin.net/json.gp?ip=' . $IP);
        $json = json_decode($details);
        if($json->geoplugin_status == '200')
            return $json->geoplugin_countryName;
        else
            return 'Error getting country name.';
    } else {
        return 'The IP is empty.';
    }
}

echo GetUserIP('192.168.0.0'); // The above function will return below, // India

The function takes the IP address and uses the file get contents() method to send an HTTP request to the API. The API delivers a json response that it decodes with json decode(), parses for the country name, and returns.

Locating a Visitor Country:

If you wish to find the visitor's location, you must send the client's IP address to the function in this manner.

GetUserIP($_SERVER['REMOTE_ADDR'])

Remember to use this on a live server because REMOTE ADDR will return the default IP address '127.0.0.1' when run from localhost.

This explains how to retrieve the country name from an IP address using the geoplugin API and PHP. The advantage of this API is that you do not need to register or receive an API key in order to use the web service. It's completely free and easy to use. I hope you enjoy it. If you find this useful, please share it on social media.

 

 

Comments

Popular posts from this blog

Latest free website directory list 2022.

How to Resolve the WordPress Error Establishing a Database Connection

Best Free WordPress Page Builders of 2022