Get Visitors Country & City through IP Address in PHP

Hey friends,

Today I will be talking about retrieving your website visitors Geographical details i.e their Country & City and then performing, some decision making based on the country and city from where your website has been accessed.

There are numerous incidences where this practice can be applied such as Currency Converter based on countries or restricting visitors from any country to visit the website by PHP itself. So I will tell you how we gonna get the details and implement the decision making.

For getting the details of user we will need to send the request to some external websites there are numerous websites available which compile the IP Address provided by you and provides you with user details. I will be sending the request to my most reliable website It’s Totally free to use.

Some prerequisites settings you should check before starting are

Firstly since we are going to use file_get_contents make sure you have enabled allow_url_fopen=On in your php.ini file.

So let’s start implementing the same.

First, let us create a file index.php and locate the IP address of anyone who accesses the page.

”, ‘city’=>”);
//Create an array having country and city as index.

if(filter_var($client, FILTER_VALIDATE_IP)){
$ip = $client;
}elseif(filter_var($forward, FILTER_VALIDATE_IP)){
$ip = $forward;
$ip = $remote;

//Validate the all 3 IP address retrieved above and assign to $ip variable

//Sending the request to Server by sending IP address which was stored in $ip variable.

$ip_data = @json_decode(file_get_contents(“”.$ip));

//If Response is not NUll then access the object and assign values to array

if($ip_data && $ip_data ->geoplugin_countryName != null){
$result [‘country’] = $ip_data ->geoplugin_countryCode;
$result [‘city’] = $ip_data ->geoplugin_city;

//Here comes the decision Making

if($result[‘country’] ==’IN’)
//Do someting
Do Something


So In above code, you saw how easy it is to track your visitors Country and City.

We have also Prepared the Demo for all our young Energetic Developers Download the Demo Here.

You can also View our other trending tutorials

Preventing SQL Injection in PHP.

Create Custom Autosuggestion Powered by Jquery & Ajax

Hope this tutorial helps our developer mates so they can face any development Hurdles that may come in their way.

Because We Believe Hurdles aren’t Really Hurdles.



  1. Amit said:

    Great article i ever read simple and very informative

    July 16, 2017
    • Saurabh Dubey said:

      Thank You Amit.

      July 17, 2017

Leave a Reply

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