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.
Contents
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
<?php
$visitorIP = $_SERVER[‘REMOTE_ADDR’];
$apiURL = ‘https://freegeoip.app/json/’.$visitorIP;
$ch = curl_init($apiURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$apiResponse = curl_exec($ch);
curl_close($ch);
$ipInfo = json_decode($apiResponse, true);
if(!empty($ipInfo)){
$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;
}else{
echo ‘IP details is not found!’;
} ?>
The post Get Geolocation from IP Address Using PHP appeared first on PhpCluster.