X
    Categories: APIPHP

How to Find Geolocation by Country IP Address in PHP

Are customers being asked to provide their country and any other location-related data on your website? If so, you can use a geolocation API to automatically get it.

To find the location of my customers for my digital product shop, I used a popular API service called geolocation.

It’s always a good idea to make it easier for end-users to enter data. It is important to make the process easy for them.

This article will show you how to use the IP address to obtain geolocation. It’s a two-step process where step1 is to get the IP address and step 2 is to get the geolocation.

 

This is an example

This example uses the geoplugin geolocation API tool to look up the location data by using the IP address.

This API endpoint searches for IPV4, IPv6 and any domain to be used as a parameter with the geolocation request.

This code performs a 2-step process in order to output the location data.

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

It will then use the IP address as the IP address to set cURL to access the geolocation data.

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

Read Also: Make Country, State and City Dropdown with REST API & jQuery

Different uses for geolocation

The IP address can be used to get the geolocation information of users.

  • It provides accurate and reliable location data, while the user can enter incorrect data.
  • It provides a 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 regional visit statistics.
  • This allows you to change the language of multilingual website content through localization.
  • It allows users to plot their location on a map layer within the UI. Google Maps JavaScript API provides Geolocation services to display the location of the users and device on a map.

Get your current IP address

index.php

<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">



<div class="min-h-screen bg-gray-100 grid items-center justify-center">

     <div class="p-6 bg-white flex items-center space-x-6 rounded-lg shadow-md hover:scale-105 transition transform duration-500 cursor-pointer">

       <div>

         <img class="bg-gray-400" src="https://www.countryflags.io/<?php echo strtolower($country['country_code']); ?>/flat/64.png" alt="">

      </div>

      <div>

        <h1 class="text-xl font-bold text-gray-700 mb-2">IP: <?php echo $ip; ?></h1>

        <p class="text-gray-600 w-80 text-sm">

           <?php if ($country['city'] != "") { ?>

               City: <?php echo $country['city']; ?><br>

           <?php } ?>

           <?php if ($country['state'] != "") { ?>

               State: <?php echo $country['state']; ?><br>

           <?php } ?>

           Country: <?php echo $country['country']; ?><br>

           Continent: <?php echo $country['continent']; ?>

        </p>

      </div>

    </div>

</div>

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

It imports the location class invokes methods to obtain and validate the IP addresses.

After the IP has been validated and returned true it will request the geolocation data. Or else, it will display the error message to the UI.

To get geolocation via PHP, prepare an API request

Request.php

<?php class Request { 

        function ip_info($ip = NULL, $purpose = "location", $deep_detect = TRUE) { 

            $output = NULL; if (filter_var($ip, FILTER_VALIDATE_IP) === FALSE) { 

            $ip = $_SERVER["REMOTE_ADDR"]; 

            if ($deep_detect) { 

                 if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP)) 

                       $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; 

                 if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP)) 

                     $ip = $_SERVER['HTTP_CLIENT_IP']; 

             }

       } 

      $purpose = str_replace(array("name", "\n", "\t", " ", "-", "_"), NULL, strtolower(trim($purpose))); 

      $support = array("country", "countrycode", "state", "region", "city", "location", "address"); 

      $continents = array( 

            "AF" => "Africa",

            "AN" => "Antarctica",

            "AS" => "Asia",

            "EU" => "Europe",

            "OC" => "Australia (Oceania)",

            "NA" => "North America",

            "SA" => "South America"

        );

        if (filter_var($ip, FILTER_VALIDATE_IP) && in_array($purpose, $support)) {

            $ipdat = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));

            if (@strlen(trim($ipdat->geoplugin_countryCode)) == 2) {

                switch ($purpose) {

                    case "location":

                        $output = array(

                            "city"           => @$ipdat->geoplugin_city,

                            "state"          => @$ipdat->geoplugin_regionName,

                            "country"        => @$ipdat->geoplugin_countryName,

                            "country_code"   => @$ipdat->geoplugin_countryCode,

                            "continent"      => @$continents[strtoupper($ipdat->geoplugin_continentCode)],

                            "continent_code" => @$ipdat->geoplugin_continentCode

                        );

                        break;

                    case "address":

                        $address = array($ipdat->geoplugin_countryName);

                        if (@strlen($ipdat->geoplugin_regionName) >= 1)

                            $address[] = $ipdat->geoplugin_regionName;

                        if (@strlen($ipdat->geoplugin_city) >= 1)

                            $address[] = $ipdat->geoplugin_city;

                        $output = implode(", ", array_reverse($address));

                        break;

                    case "city":

                        $output = @$ipdat->geoplugin_city;

                        break;

                    case "state":

                        $output = @$ipdat->geoplugin_regionName;

                        break;

                    case "region":

                        $output = @$ipdat->geoplugin_regionName;

                        break;

                    case "country":

                        $output = @$ipdat->geoplugin_countryName;

                        break;

                    case "countrycode":

                        $output = @$ipdat->geoplugin_countryCode;

                        break;

                }

            }

        }

        return $output;

    }

    function getIPAddress()

    {

        $ipaddress = '';

        if (getenv('HTTP_CLIENT_IP'))

            $ipaddress = getenv('HTTP_CLIENT_IP');

        else if (getenv('HTTP_X_FORWARDED_FOR'))

            $ipaddress = getenv('HTTP_X_FORWARDED_FOR');

        else if (getenv('HTTP_X_FORWARDED'))

            $ipaddress = getenv('HTTP_X_FORWARDED');

        else if (getenv('HTTP_FORWARDED_FOR'))

            $ipaddress = getenv('HTTP_FORWARDED_FOR');

        else if (getenv('HTTP_FORWARDED'))

            $ipaddress = getenv('HTTP_FORWARDED');

        else if (getenv('REMOTE_ADDR'))

            $ipaddress = getenv('REMOTE_ADDR');

        else

            $ipaddress = 'UNKNOWN';

        return $ipaddress;

    }

}

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

Once the IP has been validated and returned true, you can use the ip_info() function via file_get_contents to request the geoplugin API.

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

Output: API Response – Geolocation with Country

Below are images showing the location data along with code and country name.

Huzoor Bux: I am a PHP Developer

View Comments (2)