PHP

Get Geolocation from IP Address Using PHP

Get Geolocation from IP Address Using PHP

Geolocation gives data about the geographic area of a client. In particular, the IP address is utilized by the geolocation administration to decide the area. To follow the guest’s area, the principal thing required is an IP address. In light of the IP address, we can gather the geolocation data of the guest. The PHP $_SERVER variable is the most straightforward method for getting the client’s IP address. In view of the guest’s IP address, you can recognize the area with scope and longitude utilizing PHP. In this instructional exercise, we will tell you the best way to get the area from the IP address utilizing PHP.

The Geolocation API is a moment method for observing the area of a client by IP address. You can use a free Geolocation API in PHP to bring area data from an IP address. This model content will utilize IP Geolocation API to get area, country, district, city, scope, and longitude from IP address utilizing PHP.

Get IP Address of User with PHP.

Use the REMOTE_ADDR of $_SERVER to get the current client’s IP address in PHP.

$userIP = $_SERVER['REMOTE_ADDR']

Get Location from IP Address using PHP.

Use the IP Geolocation API to get the user’s location from IP using PHP.

  • Call API via HTTP GET request using cURL in PHP.
  • Convert API JSON response to array using json_decode() function.
  • Retrieve IP data from API response.

There is various info is available about geolocation in API response. Some of the most useful location details are:

  • Country Name
  • Country Code
  • Region Code
  • Region Name
  • City
  • Zip Code
  • Latitude
  • Longitude
  • Time Zone
<?php

$clientIP = $_SERVER['REMOTE_ADDR'];  
$apiURL = 'https://freegeoip.app/json/'.$clientIP; 
$curl = curl_init($apiURL);  
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  
$response = curl_exec($curl); 
curl_close($curl);  
$ipDetails = json_decode($response, true); 
if(!empty($ipDetails)){ 
$countryCode = $ipDetails['country_code']; 
$countryName = $ipDetails['country_name']; 
$regionCode = $ipDetails['region_code']; 
$regionName = $ipDetails['region_name']; 
$city = $ipDetails['city']; 
$zipCode = $ipDetails['zip_code']; 
$latitude = $ipDetails['latitude']; 
$longitude = $ipDetails['longitude']; 
$timeZone = $ipDetails['time_zone']; 

echo 'Country Name: '.$countryName.'<br/>'; 
echo 'Country Code: '.$countryCode.'<br/>'; 
echo 'Region Code: '.$regionCode.'<br/>'; 
echo 'Region Name: '.$regionName.'<br/>'; 
echo 'City: '.$city.'<br/>'; 
echo 'Zipcode: '.$zipCode.'<br/>'; 
echo 'Latitude: '.$latitude.'<br/>'; 
echo 'Longitude: '.$longitude.'<br/>'; 
echo 'Time Zone: '.$timeZone; 
}else{ 
echo 'IP data is not found!'; 
}

?>

 

Crop And Upload Image In JQuery With PHP.     Upload Image In Angular With PHP

Related Articles

Leave a Reply

Back to top button