Get visitors country and city in PHP using ipstack API

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:


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:

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:

$api_key = "YOUR_API_KEY";
$freegeoipjson = file_get_contents("".$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.

7 responses 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!

  2. maxxxi says:

    How to use this in wordpress please?

  3. steve says:

    The city returns null.

  4. abhi says:

    This api is not working..after giveing a proper ip and the access key It is returning null as all fields

    • Faruque Ahamed Mollick says:

      Did you check this on a live server? Well, it will not work if you test it on the local server of your machine.

      • Nilton Andrade says:

        I’ve tried on a live server and still it’s not returning values
        What’s the php version require to run this code?
        Thanks in advance

  5. Rameez says:

    You can also try to get visitor’s location in PHP.

Leave a Reply

Your email address will not be published.