Get Geolocation with Country by IP Address in PHP

by Vincy. Last modified on July 12th, 2022.

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 a popular geolocation API service to get the customers’ locations for my digital product shop.

It is always good to reduce the end-users effort in 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 one step1 is to get the IP address and step 2 is to get the geolocation.

What is inside?

  1. About this example
  2. Different uses of getting Geolocation
  3. File structure
  4. Get and validate the 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 the IPWhoIs geolocation API tool to look up the location data by using the IP address.

Complete Geolocation Data by IP

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

This code executes a 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 use 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 JSON response.

Different uses of getting Geolocation

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

  • It gives accuracy and dependability to the location data whereas the user may enter the wrong data.
  • It provides a single entry point to get the data that will be used in many places, like location-based currency convertors, shipping calculations and many others.
  • To calculate the visit statistics based on the region.
  • It helps to switch the language of the multilingual website content by localizing the visitors.
  • To plot the users’ location on a map layer of the UI. Google Maps JavaScript API provides Geolocation services to display the location of the users and devices on a map.

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 execute 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 Geo Location File Structure

Get and validate the current IP address

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

It imports the location service class and invokes 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.


require_once 'lib/Request.php';
$requestModel = new Request();
$ip = $requestModel->getIpAddress();
$isValidIpAddress = $requestModel->isValidIpAddress($ip);
<TITLE>Get Geo Location by the IP address</TITLE>
<link href="assets/css/style.css" type="text/css" rel="stylesheet" />
	<div class="txt-heading">Get Geo Location by the IP address</div>
if ($isValidIpAddress == "") {
    echo "<div class='error'>Invalid IP address $ip</div>";
} else {
    $geoLocationData = $requestModel->getLocation($ip);
    print "<PRE>";
	<div id="location">
		<div class="geo-location-detail">

			<div class="row">
				<div class="form-label">
					Country Name: <?php  echo $geoLocationData['country'];?>
			<div class="row">
				<div class="form-label">
					Country Code: <?php   echo $geoLocationData['country_code'];?>
			<div class="row">
				<div class="form-label">
					Ip Address: <?php  echo $geoLocationData['ip'];?>
<?php }?>

Prepare API request to get geolocation via PHP cURL

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 is validated and returns true, the getLocation() function requests the ipwhois API via the PHP cURL.

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


class Request

    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;
        } 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;

    public function isValidIpAddress($ip)
            return false;
        return true;

    public function getLocation($ip)
        $ch = curl_init('' . $ip);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $json = curl_exec($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 show the location data with the country name, and 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 provides services to access location data programmatically.

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

PHP supports integrating the GeoIP2 package of the 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 );


Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “Get Geolocation with Country by IP Address in PHP”

Leave a Reply

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

↑ Back to Top

Share this page