get region/city from ip

get region/city from ip

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

Stefan Bogdanescu

Founder & Senior Architect

Retrieving Geolocation Data from an IP Address in PHP

Retrieving geographic information like region and city from an IP address requires interacting with a third-party geolocation database. These services maintain massive mappings of IP ranges to physical locations, a task that is computationally expensive and legally complex for individual developers to replicate. Consequently, the industry standard approach is to consume these datasets via public APIs or by integrating into your own application logic.

When implementing this functionality in PHP without installing external libraries like geoip or maxmind, you must rely on HTTP requests to remote endpoints. The choice of API provider significantly impacts the accuracy and granularity of the returned data. Some services, such as api.hostip.info, provide basic latitude and longitude but often lack specific city-level precision. In contrast, providers like ipaddresslocation.org tend to return more granular data points including region names and precise city coordinates.

Implementing a Raw HTTP Request

To fetch this data without dependencies, the most straightforward method is using PHP's built-in file_get_contents() or curl. Since you cannot install external libraries, curl is generally preferred for its flexibility in handling headers and timeouts, although file_get_contents works perfectly for simple GET requests.

Here is a minimal example using curl to query a geolocation service:

<?php
function getIpLocation($ip) {
    // Ensure we are querying the actual IP if not provided
    $targetIp = ($ip === '0.0.0.0') ? $_SERVER['REMOTE_ADDR'] : $ip;
    
    $url = "http://api.ipaddresslocation.org/json?ip={$targetIp}";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Prevent hanging requests
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($response === false || $httpCode !== 200) {
        return null;
    }

    $data = json_decode($response, true);
    
    // Validate that the JSON structure is as expected before accessing keys
    if (isset($data['country'], $data['city'])) {
        return [
            'ip' => $targetIp,
            'country' => $data['country'],
            'region' => $data['region'] ?? null,
            'city' => $data['city'] ?? null,
            'latitude' => $data['lat'] ?? null,
            'longitude' => $data['lon'] ?? null
        ];
    }

    return null;
}

Evaluating Data Accuracy and Limitations

A common pitfall when selecting an API is assuming that free services provide enterprise-grade accuracy. Services like api.hostip.info are excellent for lightweight checks where high precision isn't critical, but they often fail to distinguish between neighboring cities or return generic region names (e.g., "North America" instead of a specific state).

If your application requires displaying city-specific information to users, you should verify the output against known benchmarks. The accuracy of these APIs depends on the underlying Whois database and the frequency with which ISPs update their registration data. Some mobile carriers, for instance, assign IP ranges dynamically based on cell tower location rather than static address blocks, leading to discrepancies where the returned city does not match the user's actual physical location.

Handling Failures and Edge Cases

When building a production script, you must handle scenarios where the API returns invalid data or times out. Always check the HTTP status code and validate the JSON structure before accessing specific keys like city or region. If an API does not provide region data for a specific country, your application should gracefully default to null rather than displaying broken UI elements.

Furthermore, consider caching the results. Geolocation data rarely changes in real-time; an IP address usually maps to the same location for months. Storing the result in Redis or a simple file cache can drastically reduce external API calls, lowering latency and respecting rate limits imposed by free tiers.

For projects built on Laravel, you might prefer using a dedicated package that handles these raw HTTP interactions internally, but if strict dependency constraints apply, the raw curl approach remains robust. For more advanced needs involving user privacy or legal compliance regarding data retention, consider exploring resources from https://laravelcompany.com to understand how to handle sensitive user data responsibly within your stack.

Our network