Retrieving Visitor Country from IP Address Using PHP

Nov 21, 2025 · Programming · 9 views · 7.8

Keywords: PHP | Geolocation | IP_Address | Country_Code | API

Abstract: This article explains a method to obtain the full country name of website visitors from their IP addresses using PHP. It covers the limitations of existing services that return only country codes and introduces a custom function that utilizes the geoplugin.net API for comprehensive geolocation data. The function supports various output formats and includes code examples for easy integration.

Introduction

In web development, it is often necessary to retrieve the geographic location of visitors based on their IP addresses. This can be useful for personalizing content, analytics, or security purposes. A common challenge is obtaining the full country name instead of just the two-letter country code.

Problem Analysis

Many IP geolocation services, such as hostip.info, return only the country code (e.g., "US" for United States). While this is sufficient for some applications, others require the full country name. Manually mapping codes to names is tedious and error-prone, and using pre-made CSV files may not be desirable due to maintenance or dependency issues.

Solution Overview

A robust solution is to use an API that provides detailed location information, such as the geoplugin.net service, which offers a free JSON API returning comprehensive data including the country name. By integrating this API into a PHP function, we can easily retrieve the desired information.

Code Implementation

The following PHP function, ip_info, handles IP address retrieval and geolocation. It validates the IP address, fetches data from geoplugin.net, and returns various details based on the specified purpose.

<?php
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", "
", "	", " ", "-", "_"), 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;
}
?>

This function first checks if a valid IP address is provided; if not, it retrieves the visitor's IP address, considering proxies via HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP. It then fetches JSON data from geoplugin.net and parses it to return the requested information.

Usage Examples

Here are some examples of how to use the ip_info function:

<?php
// Get country name for the visitor
echo ip_info(NULL, "country"); // Outputs e.g., "United States"

// Get country code
echo ip_info(NULL, "countrycode"); // Outputs e.g., "US"

// Get full location details
print_r(ip_info(NULL, "location")); // Outputs an array with city, state, country, etc.

// For a specific IP
echo ip_info("173.252.110.27", "country"); // Outputs "United States"
?>

Advantages and Limitations

The geoplugin.net API is free and easy to use, providing accurate data for most IP addresses. However, it may have rate limits or occasional inaccuracies. Using external APIs introduces dependency, so for high-traffic sites, consider caching or alternative services.

Conclusion

By leveraging the geoplugin.net API through a custom PHP function, developers can efficiently retrieve full country names and other location details from IP addresses. This approach avoids the need for manual code mappings and integrates seamlessly into web applications.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.