Getting visitors country from their IP

Getting visitors country from their IP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Retrieving Full Country Names from IP Addresses

Your current implementation correctly identifies the client's public IP address by prioritizing HTTP_CLIENT_IP, then checking HTTP_X_FORWARDED_FOR, and finally falling back to REMOTE_ADDR. This logic is standard for handling requests that might pass through load balancers or proxies. However, you are hitting a limitation with the specific endpoint from hostip.info: it returns ISO 3166-1 alpha-2 country codes (e.g., "US", "CA") rather than human-readable names.

While it is technically trivial to build a massive associative array in PHP mapping every two-letter code to its full name, you explicitly want to avoid maintaining that data locally. You also ruled out downloading static CSV files or using pre-compiled IP-to-country libraries. The solution lies in leveraging third-party APIs that provide the full country name directly in their JSON response.

Switching to a Name-Based API

The most direct alternative to the simple query string you are currently using is to utilize an API that returns structured data containing the field for the country name. Services like ipapi.co or ipapi.com offer free tiers that return JSON objects including the country_name field.

Here is how you can modify your PHP logic to fetch the full name instead of the code:

$real_ip_adress = $cip; // Assuming your existing IP detection logic set $cip already

// Using ipapi.co which returns JSON with 'country_name'
$url = 'https://ipapi.co/json/?ip=' . $real_ip_adress;
$options = [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => ['Accept: application/json']
];
$context = stream_context_create($options);

$response = file_get_contents($url, false, $context);

if ($response === false) {
    // Handle connection error (timeout, DNS failure, etc.)
    echo "Error fetching IP data.";
} else {
    $data = json_decode($response, true);
    
    if ($data && isset($data['country_name'])) {
        echo $data['country_name']; 
    } else {
        // Fallback or error handling for invalid IPs
        echo "Country name not available.";
    }
}

This approach eliminates the need for a local mapping table. The API handles the translation from the IP address to the full English name automatically. Note that ipapi.co is particularly useful here because it provides the name without requiring you to maintain a local database of country codes.

Handling Edge Cases and Trustworthiness

Before integrating this into production, consider how your application handles proxy headers. Your existing code checks HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR. If a user is behind a corporate firewall or a CDN like Cloudflare, the REMOTE_ADDR will point to the proxy, not the end-user.

Most robust APIs allow you to pass the original client IP directly via a query parameter if the API supports it, but many simply return the data for the IP address they see on their wire (the proxy's IP). If you need the true origin IP despite proxies, you must trust that your reverse proxy is configured correctly or that the upstream service provides a specific header like CF-Connecting-IP (for Cloudflare) which you would need to parse before sending to the location API.

Furthermore, rely on HTTPS for these requests. While file_get_contents can work over HTTP, exposing your backend to make unencrypted calls to third-party geolocation services is a security risk. Always ensure your API calls use the secure scheme provided by the vendor.

Cost and Rate Limiting Considerations

When selecting an alternative to hostip.info, you must evaluate the rate limits of the free tier. Services like ipapi.co typically allow around 1,000 requests per month for free plans. If your application has high traffic, this limit could be reached quickly, potentially blocking legitimate users or causing your application to fail if it doesn't handle HTTP 429 (Too Many Requests) errors gracefully.

You might consider implementing a caching layer in Redis or Memcached. Since country data rarely changes, you can cache the result of the API call for an IP address for several hours. This drastically reduces the number of external requests and keeps you well within any free-tier limits while ensuring consistent performance.

Our network