Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Get Geolocation with Country by IP Address in PHP

#1
Get Geolocation with Country by IP Address in PHP

by Vincy. Last modified on May 2nd, 2021.

Is your website asking the customers to enter their country or any location related data? if so, it is better to get it automatically by using a geolocation API.

I have used one a popular geolocation API service to get the customers’ location for my digital product shop.

It is always good to reduce the end-user’s effort from entering data. We should make them feel good by making the process seamless.

We will see how to get geolocation with country name and code using the IP address. It’s a two step process where the step1 is to get the IP address and the step 2 is to get the geolocation.

Complete Geolocation Data by IP

What is inside?


  1. About this example
  2. Different uses of getting Geolocation
  3. File structure
  4. Get and validate current IP address
  5. Prepare API request to get geolocation via PHP cURL
  6. Output: API response – geolocation with country
  7. Alternate Geolocation API

About this example


This example uses IPWhoIs geolocation API tool to lookup the location data by using the IP address.

This API endpoint looks for any IPV4, IPv6 or any domain as a parameter along with the geolocation request to read.

This code executes 2-step process to output the location data.

It creates a PHP service with a function to get the user IP address from the $_SERVER array.

Then, it will uses the IP address to set the cURL option to read the geolocation data.

This will output the country name, code and the given IP by parsing the API response.

Different uses of getting Geolocation


There are more uses of getting the geolocation of the users by the IP address.

  • It gives accuracy and dependability of the location data where as the user may enter wrong data.
  • It provides single entry point to get the data that will be used in many places, like location-based currency convertor, shipping calculation or many.
  • To calculate the visits statistics based on the region.
  • It helps to switch language of the multilingual website content by localising the visitors.

File structure


The below file structure image shows the simplicity of this example with the minimal number of files.

The Request.php file has the prime functions that executes the two steps to get IP and geolocation data.

The index.php file calls the service to get the location data and populate them in the UI.

Get and validate current IP address


This is the home page code which contains the HTML code to acknowledge users with the geolocation data.

It imports the location service class invoke the methods to get and validate the IP address.

Once the IP is validated and returns true, it requests the geolocation data. Or else, it will display the error message to the UI.

index.php

<?php
require_once 'lib/Request.php';
$requestModel = new Request();
$ip = $requestModel->getIpAddress();
$isValidIpAddress = $requestModel->isValidIpAddress($ip);
?>
<HTML>
<HEAD>
<TITLE>Get Geo Location by the IP address</TITLE>
<link href="assets/css/style.css" type="text/css" rel="stylesheet" />
</HEAD>
<BODY> <div class="txt-heading">Get Geo Location by the IP address</div> <?php
if ($isValidIpAddress == "") { echo "<div class='error'>Invalid IP address $ip</div>";
} else { $geoLocationData = $requestModel->getLocation($ip); ?> <div id="location"> <div class="geo-location-detail"> <div class="row"> <div class="form-label"> Country Name: <?php echo $geoLocationData['country'];?> </div> </div> <div class="row"> <div class="form-label"> Country Code: <?php echo $geoLocationData['country_code'];?> </div> </div> <div class="row"> <div class="form-label"> Ip Address: <?php echo $geoLocationData['ip'];?> </div> </div> </div> </div>
<?php }?>
</BODY>
</HTML>

Prepare API request to get geolocation via PHP cURL


The getIPAddress() function builds a if-else-if ladder of majority of the scenario to get the non-empty IP address using the $_SERVER variable.

Once the IP is validated and returns true, the getLocation() function to request the ipwhois API via cURL.

The API will return a JSON response as a result. This example decodes the response and parses the geolocation data to get the country details from it.

lib/Request.php


<?php class Request
{ /** * Retrieves IP address set in the request header. * * Each ISPs sets them following their own logic. There is also a possibility for the user * to easily spoof their IP address. * * So using this for mission critical situations is not advisable. * If you are getting the IP address for casual logging purposes, then this is fine. */ public function getIpAddress() { $ipAddress = ''; if (! empty($_SERVER['HTTP_CLIENT_IP']) && $this->isValidIpAddress($_SERVER['HTTP_CLIENT_IP'])) { // check for shared ISP IP $ipAddress = $_SERVER['HTTP_CLIENT_IP']; } else if (! empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { // check for IPs passing through proxy servers // check if multiple IP addresses are set and take the first one $ipAddressList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); foreach ($ipAddressList as $ip) { if ($this->isValidIpAddress($ip)) { $ipAddress = $ip; break; } } } else if (! empty($_SERVER['HTTP_X_FORWARDED']) && $this->isValidIpAddress($_SERVER['HTTP_X_FORWARDED'])) { $ipAddress = $_SERVER['HTTP_X_FORWARDED']; } else if (! empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']) && $this->isValidIpAddress($_SERVER['HTTP_X_CLUSTER_CLIENT_IP'])) { $ipAddress = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP']; } else if (! empty($_SERVER['HTTP_FORWARDED_FOR']) && $this->isValidIpAddress($_SERVER['HTTP_FORWARDED_FOR'])) { $ipAddress = $_SERVER['HTTP_FORWARDED_FOR']; } else if (! empty($_SERVER['HTTP_FORWARDED']) && $this->isValidIpAddress($_SERVER['HTTP_FORWARDED'])) { $ipAddress = $_SERVER['HTTP_FORWARDED']; } else if (! empty($_SERVER['REMOTE_ADDR']) && $this->isValidIpAddress($_SERVER['REMOTE_ADDR'])) { $ipAddress = $_SERVER['REMOTE_ADDR']; } return $ipAddress; } /** * To validate if an IP address is both a valid and does not fall within * a private network range. * * @access public * @param string $ip */ public function isValidIpAddress($ip) { if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) { return false; } return true; } public function getLocation($ip) { $ch = curl_init('http://ipwhois.app/json/' . $ip); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $json = curl_exec($ch); curl_close($ch); // Decode JSON response $ipWhoIsResponse = json_decode($json, true); // Country code output, field "country_code" return $ipWhoIsResponse; }
}

Output: API response – geolocation with country


The below images shows the location data with country name, code.

Get-Geo Location Valid Ip Address

If the IP address is not a valid one, then the code will return the error message to acknowledge the user.

Get Geo Location Invalid Ip Address

Alternate Geolocation API


These are some of the alternatives API providing services to access location data programatically.

  1. GeoPlugin service allow access from PHP, ASP, JavaScript and more.
  2. IPinfo library to get location via token-based authentication.

PHP supports to integrate GeoIP2 package of PECL extension to get the location data by using predefined functions. The code to get the country name from the IP address or domain name is,


geoip_country_name_by_name ( $hostname )

Download

↑ Back to Top



https://www.sickgaming.net/blog/2021/04/...ss-in-php/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] How to Get the Client User IP Address in PHP xSicKxBot 0 201 09-09-2020, 07:08 AM
Last Post: xSicKxBot
  [Tut] How to Get the Client User IP Address in PHP xSicKxBot 0 228 08-14-2020, 09:14 PM
Last Post: xSicKxBot
  [Tut] Address Book – Acan xSicKxBot 0 246 07-15-2020, 08:43 PM
Last Post: xSicKxBot

Forum Jump:

[-]
Active Threads
(Indie Deal) God Eater 3, DRAGON BALL, T...
Last Post: xSicKxBot
Today 10:20 AM
» Replies: 0
» Views: 6
Microsoft - Making remote and hybrid mee...
Last Post: xSicKxBot
Today 05:33 AM
» Replies: 0
» Views: 7
News - JAVA EDITION: SNAPSHOT 21W19A
Last Post: xSicKxBot
Today 05:31 AM
» Replies: 0
» Views: 7
News - Koei Tecmo’s Guzzler Joins Hamste...
Last Post: xSicKxBot
Today 05:30 AM
» Replies: 0
» Views: 8
News - Sega Looking To Release Brand New...
Last Post: xSicKxBot
Today 05:30 AM
» Replies: 0
» Views: 7
Xbox Wire - Xbox Spotlight: Mental Healt...
Last Post: xSicKxBot
Today 05:30 AM
» Replies: 0
» Views: 7
News - Live services push EA to $6.19 bi...
Last Post: xSicKxBot
Today 05:29 AM
» Replies: 0
» Views: 46
News - Blog: Improving the ‘About This G...
Last Post: xSicKxBot
Today 05:29 AM
» Replies: 0
» Views: 41
[Tut] How to Check the Pandas Version in...
Last Post: xSicKxBot
Yesterday 08:38 PM
» Replies: 0
» Views: 8
(Indie Deal) NBA 2K21, MY HERO ONE'S JUS...
Last Post: xSicKxBot
Yesterday 08:37 PM
» Replies: 0
» Views: 6

[-]
Twitter

Copyright © SickGaming.net 2012-2020