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:
$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:
- Get the distance between two places in PHP with Google Map API
- Locate the Geo-position of a visitor in JavaScript
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.
How would one go about showing one div to lets say Europe and another div to the rest of the world? Thank you!
How to use this in wordpress please?
The city returns null.
This api is not working..after giveing a proper ip and the access key It is returning null as all fields
Did you check this on a live server? Well, it will not work if you test it on the local server of your machine.
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
You can also try ipgeolocation.io to get visitor’s location in PHP.