Get Geolocation from IP Address Using PHP

In a web application, are you asking visitors to select the country name or city name, or any other location-related information? If yes, you can use geolocation API to do the same thing.

Geolocation provides information about the geographic location details of the visitors. This API uses the IP addresses to get the geographic details of the visitors.

So, to track the all details we need visitors’ IP addresses. Using an IP address, we get all geolocation details easily.

In this tutorial, we are going to see how to get geolocation from IP addresses using PHP.

Here we will use a free geolocation API to get location details by IP address.

Step 1: Get IP Address of User with PHP

$visitorIP = $_SERVER[‘REMOTE_ADDR’];

Step 2: Get Location from IP Address in PHP with Geolocation API

$visitorIP = $_SERVER[‘REMOTE_ADDR’];
$apiURL = ‘’.$visitorIP;

$ch = curl_init($apiURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$apiResponse = curl_exec($ch);

$ipInfo = json_decode($apiResponse, true);


$country_code = $ipInfo[‘country_code’];
$country_name = $ipInfo[‘country_name’];
$region_name = $ipInfo[‘region_name’];
$region_code = $ipInfo[‘region_code’];
$city = $ipInfo[‘city’];
$zip_code = $ipInfo[‘zip_code’];
$latitude = $ipInfo[‘latitude’];
$longitude = $ipInfo[‘longitude’];
$time_zone = $ipInfo[‘time_zone’];

echo ‘Country Name: ‘.$country_name.'<br>’;
echo ‘Country Code: ‘.$country_code.'<br>’;
echo ‘Region Name: ‘.$region_name.'<br>’;
echo ‘Region Code: ‘.$region_code.'<br>’;
echo ‘City: ‘.$city.'<br>’;
echo ‘Zipcode: ‘.$zip_code.'<br>’;
echo ‘Latitude: ‘.$latitude.'<br>’;
echo ‘Longitude: ‘.$longitude.'<br>’;
echo ‘Time Zone: ‘.$time_zone;
echo ‘IP details is not found!’;
} ?>

Also Read: Get Country and City Name Using IP Address in PHP

So, In this article, you have learned how to fetch geolocation in PHP using an IP address.

If you liked this tutorial, don’t forget to share it on social media. If you have any queries, write in the given below comment section.

The post Get Geolocation from IP Address Using PHP appeared first on PhpCluster.

Leave a Reply

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