Get visitors country and city in PHP using freegeoip API

By Faruque Ahamed Mollick

———————————-

 

The freegeoip API has been depreciated and no more working. Visit this tutorial to get visitors country and city using ipstack API

The code of this post is not working now.
 Here is the solution using ipstack API.



————————————

 

Here I am going to give you a simple and easy tutorial which may very helpful for developers. In this tutorial, I am going to tell you how to get your visitor’s geo location (Country and city) using PHP code and freegeoip public HTTP API.

Get visitors country and city in PHP using ipstack API

 

freegeoip.net provides a public HTTP API for developers to search the geolocation of IP addresses. It uses a database of IP addresses that are associated with cities along with other relevant information like timezone, latitude, and longitude.

Freegeoip link to get JSON location data of IP

Below is the link structure of freegeoip which showing various types of data for a particular IP address:

http://freegeoip.net/json/PUT_THE_IP_ADDRESS

Suppose the IP address of a visitor is 25.15.103.201. Then the URL of freegeoip will be:

http://freegeoip.net/json/25.15.103.201

It will show you a JSON data. You have to use this JSON data to get the country and city of the particular visitor.

As this will use visitors IP address to get the location, so you must need to get the IP address of the visitor.

PHP code to get the IP of visitors

Below is the PHP code which can get the IP address for that particular visitor’s device:

$ip = $_SERVER['REMOTE_ADDR'];

Complete PHP code to get visitor’s location

Below is the complete code which will show visitor’s country and city name:

<?php
$ip = $_SERVER['REMOTE_ADDR']; 
$freegeoipjson = file_get_contents("http://freegeoip.net/json/". $ip ."");

$jsondata = json_decode($freegeoipjson);
$countryfromip = $jsondata->country_name;
$cityfromip = $jsondata->city;

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

In the above code, I have first take the visitor’s IP address inside a variable $ip and then use it in the freegeoip URL. Then I have decoded the JSON data using json_decode PHP function and extract city name, country name from JSON. Then echo it to show the city and country name on the web page.

This code may be useful for developers where you are going to show something on web page depending upon country or location. Well, sometime this process may not show you the accurate city. But in the case of showing the country name, it is accurate almost in all the cases. So it is better to use this process where you need to get the country location of the visitors on your site.

Leave a Reply

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