When developing custom website projects, it’s common to need the user’s country information for personalisation, analytics, or security reasons. For example, an eCommerce site might show prices in the local currency, or a streaming service might enforce geo-restrictions.

In this tutorial, we’ll use PHP and a free geolocation API to determine the country from an IP address. This method is lightweight, accurate, and compatible with both IPv4 and IPv6 addresses. Whether you’re part of a web development team or seeking to hire a PHP developer for your project, this step-by-step guide will help you incorporate IP-based geolocation into your website.

Why Get Country from IP Address?

Integrating IP-based location detection is beneficial in many web development services:

  • Content personalization – Display language, currency, and offers based on the visitor’s country.
  • Security – Block suspicious traffic from specific regions.
  • Analytics – Track where your users are coming from.
  • Compliance – Follow regional laws like GDPR.

Folder Structure

To keep the project clean, we’ll structure it as follows:

                                        /project-folder/
├── index.php              # Form with captcha
├── lib/
│   ├──Request.php
                                    

This modular approach is considered best practice in custom website development because it separates logic from presentation.

Step 1 – index.php: Creating the IP Form and Displaying Results

This file:

  • Loads the Request class
  • Accepts IP input from the user or uses the visitor’s IP
  • Validates the IP address
  • Retrieves and displays country information

                                        <?php
require_once 'lib/Request.php';
$requestModel = new Request();
$ip = $_POST['ip_address'] ?? $requestModel->getIpAddress();
$isValidIpAddress = $requestModel->isValidIpAddress($ip);
?>
<html>
<head>
<title>Get Country from IP</title>
<link href="assets/css/style.css" rel="stylesheet">
</head>
<body>
<div class="txt-heading">Get Country from IP Address</div>
<form method="POST" action="">
<label>Enter IP address:</label><br>
<input type="text" name="ip_address" value="<?php echo htmlspecialchars($ip); ?>" placeholder="e.g., 8.8.8.8">
<button type="submit">Find Country</button>
</form>
<br>
<?php if (!$isValidIpAddress): ?>
<div class='error'>Invalid IP address: <?php echo htmlspecialchars($ip); ?></div>
<?php else:
$geoLocationData = $requestModel->getLocation($ip); ?>
<div id="location">
<div class="geo-location-detail">
<div>Country Name: <strong><?php echo $geoLocationData['country']; ?></strong></div>
<div>Country Code: <strong><?php echo $geoLocationData['country_code']; ?></strong></div>
<div>IP Address: <strong><?php echo $geoLocationData['ip']; ?></strong></div>
</div>
</div>
<?php endif; ?>
</body>
</html>
                                    

Step 2 – Request.php: Handling IP Retrieval, Validation, and API Calls

In PHP web development services, separating business logic into individual classes enhances maintainability and scalability. Here’s the Request class:

                                        <?php
class Request
{
    /**
     * Get the IP address of the current client.
     */
    public function getIpAddress()
    {
        $ipAddress = '';

        if (!empty($_SERVER['HTTP_CLIENT_IP']) && $this->isValidIpAddress($_SERVER['HTTP_CLIENT_IP'])) {
            $ipAddress = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ipList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach ($ipList as $ip) {
                if ($this->isValidIpAddress(trim($ip))) {
                    $ipAddress = trim($ip);
                    break;
                }
            }
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED']) && $this->isValidIpAddress($_SERVER['HTTP_X_FORWARDED'])) {
            $ipAddress = $_SERVER['HTTP_X_FORWARDED'];
        } elseif (!empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']) && $this->isValidIpAddress($_SERVER['HTTP_X_CLUSTER_CLIENT_IP'])) {
            $ipAddress = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_FORWARDED_FOR']) && $this->isValidIpAddress($_SERVER['HTTP_FORWARDED_FOR'])) {
            $ipAddress = $_SERVER['HTTP_FORWARDED_FOR'];
        } elseif (!empty($_SERVER['HTTP_FORWARDED']) && $this->isValidIpAddress($_SERVER['HTTP_FORWARDED'])) {
            $ipAddress = $_SERVER['HTTP_FORWARDED'];
        } elseif (!empty($_SERVER['REMOTE_ADDR']) && $this->isValidIpAddress($_SERVER['REMOTE_ADDR'])) {
            $ipAddress = $_SERVER['REMOTE_ADDR'];
        }

        // For localhost testing
        if ($ipAddress === '127.0.0.1' || $ipAddress === '::1') {
            $ipAddress = '8.8.8.8'; // fallback IP (Google DNS)
        }

        return $ipAddress;
    }

    /**
     * Validates whether the IP address is public and correctly formatted.
     */
    public function isValidIpAddress($ip)
    {
        return filter_var($ip, FILTER_VALIDATE_IP, 
            FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6 | 
            FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false;
    }

    /**
     * Calls the ipwhois.app API to get country info from IP.
     */
    public function getLocation($ip)
    {
        $url = 'http://ipwhois.app/json/' . urlencode($ip);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT'] ?? 'PHP-IP-Fetcher');
        $response = curl_exec($ch);
        curl_close($ch);

        $data = json_decode($response, true);

        // Check for success response
        if (!isset($data['country'])) {
            return [
                'country' => 'Unknown',
                'country_code' => 'N/A',
                'ip' => $ip
            ];
        }

        return [
            'country' => $data['country'] ?? 'Unknown',
            'country_code' => $data['country_code'] ?? 'N/A',
            'ip' => $data['ip'] ?? $ip
        ];
    }
}
                                    

How This Works

  1. Get the Client IP – The script checks multiple $_SERVER variables to detect the actual client IP, even if behind a proxy.
  2. Validate the IP – Ensures the IP is a public IPv4 or IPv6.
  3. Fetch Location Data – Uses ipwhois.app API via cURL.
  4. Display Results – Shows country name, country code, and IP.

Sample Output

Entering 8.8.8.8 would show:

  • Country Name: United States
  • Country Code: US
  • IP Address: 8.8.8.8

Best Practices for IP Geolocation in PHP

  • Cache results to avoid repeated API calls.
  • Use a premium API key for higher accuracy and more data fields.
  • Integrate this into your custom website development projects for tailored user experiences.
  • If you hire a PHP developer, ensure they follow a modular approach for better maintainability.

Final Words

Finding the country from an IP address in PHP is straightforward and very useful for web development projects. By using a modular structure and a free API, you can quickly add geolocation to your applications. Whether you run a web development business or work with a dedicated team, this feature can boost personalisation, enhance security, and deliver better analytics.

If you’re looking to add features like this to your project, you can hire a PHP developer or collaborate with an experienced web development company to ensure robust and scalable solutions.

Tech Stack & Version

Frontend

  • HTML5
  • CSS3

Backend

  • PHP 8.1
  • cURL
  • ipwhois.app API

Deployment

  • AWS
  • DigitalOcean
  • Heroku
img

©2025Digittrix Infotech Private Limited , All rights reserved.