How to Get Country Name from IP Address with PHP

On 1/15/2018

Hi! In this post, let's see how to get country name from ip address using php. When working on multilingual web applications, it is mandatory to find the geographic location of the visitors, so that you can provide the contents that match the specific location. Some websites even change country flags and themes accordingly.

With PHP, you can get the visitor's IP easily, but unfortunately there's no way to get the country details from it. Hence, you have to rely on external web services to provide the location details. Here I'm going to show you how to find the country of visitors with the help of GeoPlugin API and PHP.

php get country name from ip address

Getting Country Name from IP Address with GeoPlugin:

GeoPlugin is a free web service that provides geographical location of site visitors from IP. It offers various types of services like PHP, JSON etc., and in this tutorial, I'm going to use the JSON API to find the country name.

You have to access the service with this url,

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

The API will return the name of the country along with other details related to the location, such as city, currency, latitude, longitude, etc.

Below I have created a PHP function getIP(). It accepts the IP Address as a parameter, communicates with the geoPlugin api and returns the country name for that IP.

PHP Function:

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

Usage:

You must call the function like this,

<?php
echo getIP('17.142.180.78');

// output
// United States 
?>

What the function does is, take the ip address and send the http request to the api using file_get_contents() method. The api returns the json response, which it decodes with json_decode(), parses for the country name and returns it.

Finding Visitor Country Location:

In case you want to find the visitor's location, you must pass the client ip address to the function in this way,

<?php echo getIP($_SERVER['REMOTE_ADDR']); ?>

Keep in mind to use this on live server, because REMOTE_ADDR will return the default ip '127.0.0.1' when you run it from localhost.

Read Also:

That explains about getting country name from IP address using geoplugin api and php. The good thing about this API is you do not need to register or obtain an API key to use the web service. It's totally free and simple to use. I hope you like this. Please share this on social networks if you find it useful.

No comments:

Post a Comment

Contact Form

Name

Email *

Message *