Get visitors country and city in PHP using ipstack API

By Faruque Ahamed Mollick

Today I am going to show you how you can get the country and city of the visitor of a web page in PHP. From the title of this tutorial, you can guess that I am going to use ipstack API.

ipstack API use the IP address of the user to get the location by IP of the user.  So, first of all, we need to get the IP of the user who visit on the web page. It is quite easy to get the IP address of the visitor in PHP.

Below is the code to get the IP address of the user:



$ip = $_SERVER['REMOTE_ADDR'];

Simple, isn’t it?

Now we need to get the API key from ipstack. To get it you have to visit their website and sign up. The free plan will let you call for 10,000 requests per month.

After you get the API key, you need to pass the IP address to the ipstack API URL like you can see below:

http://api.ipstack.com/IP_ADDRESS?access_key=API_KEY

After you replace the IP_ADDRESS with real a real IP address and API_KEY with your own ipstack API key, you will get the JSON data which contains the location data of the user. You just need to open the URL on your browser and you will able to see the data.

From the JSON data, you can easily extract the country and city of the visitor.

Below is the complete code:

<?php
$ip = $_SERVER['REMOTE_ADDR']; 
$api_key = "YOUR_API_KEY";
$freegeoipjson = file_get_contents("http://api.ipstack.com/".$ip."?access_key=".$api_key."");

$jsondata = json_decode($freegeoipjson);

$countryfromip = $jsondata->country_name;
$cityfromip = $jsondata->city;

echo "City: ". $cityfromip ."";
echo "<br/>";
echo "Country: ". $countryfromip ."";
?>

In the above code, we have first decoded the JSON file and converted it into an array. From that array, we get the country and city name of the visitor who visits our web page.

Also, read:

Even we can get region name, latitude, longitude and so on from the array.

 

So, you can see that we have successfully get country from IP address as well as the city using ipstack API key.

One response to “Get visitors country and city in PHP using ipstack API”

  1. Klaas says:

    How would one go about showing one div to lets say Europe and another div to the rest of the world? Thank you!

Leave a Reply

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