How to Geolocate an IP Address with PHP
Learn local and hosted IP geolocation in PHP with IPv6 validation, trusted proxy handling, accuracy limits, caching, and complete code.

Short answer: PHP cannot infer a location from an IP by itself. Give it a GeoIP database or call a geolocation service, validate the address, then treat the result as an estimate. For self-hosting, MaxMind’s GeoIP2 PHP package and a local GeoIP2 or GeoLite2 database avoid a network request on every lookup. A hosted service reduces database maintenance but adds credentials, latency, quotas, and an availability dependency.
This guide covers both designs, IPv4 and IPv6 handling, trusted proxy rules, complete code, failure handling, caching, and what country, city, and coordinates really mean.
1. Choose a local database or hosted API
| Concern | Local database | Hosted API |
|---|---|---|
| Latency | Local file access after initialization | Network round trip and provider processing |
| Freshness | You schedule downloads and updates | Provider maintains the data |
| Privacy | Lookup stays in your infrastructure | Queried IP is sent to a provider |
| Operations | Monitor file age, storage, and corruption | Manage tokens, timeouts, quotas, and outages |
| Cost | License or account terms plus storage | Plan or per-request quota |
MaxMind documents local database readers and web-service clients in its GeoIP documentation. The maintained PHP integration is the GeoIP2 PHP package. PHP’s legacy GeoIP extension reads legacy files and does not support current GeoIP2 databases.
2. Local lookup with MaxMind GeoIP2
Install the package
composer require geoip2/geoip2-php
Download a database permitted for your use, such as GeoLite2-City or a licensed GeoIP2-City file. Unpack it outside the public web root and keep its absolute path in configuration. Pin the Composer dependency in composer.lock; update the database separately.

Complete PHP example
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use GeoIp2\Database\Reader;
use GeoIp2\Exception\AddressNotFoundException;
use GeoIp2\Exception\InvalidDatabaseException;
function geolocate(string $ip, string $databasePath): ?array {
$validated = filter_var($ip, FILTER_VALIDATE_IP);
if ($validated === false) throw new InvalidArgumentException('Invalid IPv4 or IPv6 address');
$reader = new Reader($databasePath);
try {
$record = $reader->city($validated);
return [
'ip' => $validated,
'country_code' => $record->country->isoCode,
'country' => $record->country->name,
'region' => $record->mostSpecificSubdivision->name,
'city' => $record->city->name,
'postal_code' => $record->postal->code,
'latitude' => $record->location->latitude,
'longitude' => $record->location->longitude,
'accuracy_radius_km' => $record->location->accuracyRadius,
];
} catch (AddressNotFoundException $e) {
return null;
} finally {
$reader->close();
}
}
$ip = $_GET['ip'] ?? '';
try {
$result = geolocate($ip, __DIR__ . '/../data/GeoIP2-City.mmdb');
header('Content-Type: application/json');
echo json_encode(['data' => $result], JSON_THROW_ON_ERROR);
} catch (InvalidArgumentException $e) {
http_response_code(400);
echo json_encode(['error' => $e->getMessage()]);
} catch (InvalidDatabaseException $e) {
error_log('Invalid GeoIP database: ' . $e->getMessage());
http_response_code(503);
echo json_encode(['error' => 'Geolocation temporarily unavailable']);
}
The city() call exposes country, subdivision, city, postal, and location objects. A country-only database has fewer fields, so choose the product that matches your requirements.
Reuse the reader in workers
Opening the database per request is straightforward for PHP-FPM. In a long-running worker, initialize one reader per worker and close it during shutdown. Restart workers after replacing the .mmdb file so they do not hold an old handle.
3. Get the correct client IP
REMOTE_ADDR is the peer connected to PHP. Behind a reverse proxy or load balancer, that may be the proxy. Headers such as X-Forwarded-For can contain the original client, but clients can spoof them unless your proxy strips and rewrites them.
Configure trusted proxy CIDRs. Only when the immediate peer is trusted should you parse the forwarding header. Walk addresses from right to left, remove trusted hops, and use the first remaining valid address. If you cannot establish this trust boundary, use REMOTE_ADDR.
<?php
function clientIp(array $server, array $trustedCidrs): string {
$peer = $server['REMOTE_ADDR'] ?? '';
if (!filter_var($peer, FILTER_VALIDATE_IP)) return '';
if (!ipInCidrs($peer, $trustedCidrs)) return $peer;
$values = array_map('trim', explode(',', $server['HTTP_X_FORWARDED_FOR'] ?? ''));
for ($i = count($values) - 1; $i >= 0; $i--) {
if (filter_var($values[$i], FILTER_VALIDATE_IP) && !ipInCidrs($values[$i], $trustedCidrs)) return $values[$i];
}
return $peer;
}
Implement ipInCidrs with binary matching for IPv4 and IPv6, or use a reviewed networking library. Never accept a query parameter as the visitor address for authorization or fraud decisions.
4. Hosted service pattern
A hosted API is useful when you do not want to distribute database files. Use the provider’s official PHP client where available, store the token in an environment variable, set connect and total timeouts, and distinguish “no record” from network failure. MaxMind recommends official clients for its web services. IPinfo’s official PHP library documents city, region, country, postal code, latitude, and longitude fields.
<?php
$token = getenv('IPINFO_TOKEN');
$ip = filter_var($_GET['ip'] ?? '', FILTER_VALIDATE_IP);
if (!$token || $ip === false) { http_response_code(400); exit('Missing token or invalid IP'); }
$url = 'https://ipinfo.io/' . rawurlencode($ip) . '?token=' . rawurlencode($token);
$ch = curl_init($url);
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_CONNECTTIMEOUT => 3, CURLOPT_TIMEOUT => 8, CURLOPT_HTTPHEADER => ['Accept: application/json']]);
$payload = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); $error = curl_error($ch); curl_close($ch);
if ($payload === false || $status >= 500) throw new RuntimeException('Provider unavailable: ' . $error);
if ($status >= 400) { http_response_code(502); exit('Provider rejected the request'); }
echo $payload;
Confirm endpoint paths, fields, authentication, retention, and quotas in the provider documentation before production use.
Consume your PHP endpoint
curl --fail --get 'https://example.com/geoip.php' --data-urlencode 'ip=203.0.113.10'
import requests
r = requests.get('https://example.com/geoip.php', params={'ip': '203.0.113.10'}, timeout=5)
r.raise_for_status()
print(r.json())
const q = new URLSearchParams({ ip: '203.0.113.10' });
const res = await fetch(`https://example.com/geoip.php?${q}`, { signal: AbortSignal.timeout(5000) });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
console.log(await res.json());
5. IPv4, IPv6, and special addresses
- Validate both families with
FILTER_VALIDATE_IPand store the canonical value. - Private, loopback, and link-local ranges identify local networks, not public geography. Return “private” instead of querying a provider.
- Reject IPv6 zone IDs such as
fe80::1%eth0. MaxMind’s web-service guidance accepts canonical IPv6 notation and rejects zone IDs. - Documentation addresses such as
203.0.113.10may have no useful record. - Treat
AddressNotFoundExceptionas an expected unknown result.
6. What accuracy means
MaxMind states that “IP geolocation is inherently imprecise.” Its current guidance estimates 99.8% country-level accuracy, around 80% U.S. state or region accuracy, and around 66% U.S. city accuracy within a 50 km radius. These are MaxMind estimates, not universal guarantees.

The accuracy radius describes an area, not a confidence circle centered on the returned coordinate. Do not treat coordinates as a home, street, or exact position. VPNs, proxies, hosting networks, mobile carriers, ISP routing, and privacy opt-outs can make the observed address differ from the user. Use country or broad region for personalization; require a user-provided address or GPS permission for precision.
7. Production checklist
- Validate every address and support IPv4 and IPv6.
- Define a trusted proxy boundary before reading forwarding headers.
- Keep databases outside the web root and pin Composer dependencies.
- Automate database updates and alert on stale, missing, or invalid files.
- Cache normalized addresses with a documented TTL and privacy policy.
- For hosted calls, set timeouts, enforce quotas, and use bounded retries for transient errors.
- Return an explicit unknown state instead of guessing.
- Do not use IP geolocation alone for identity proof, legal jurisdiction, emergency location, or access control.
8. Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| Reader class not found | Missing package or autoloader | Run Composer and require vendor/autoload.php. |
| Invalid database exception | Wrong path, compressed file, partial download, or corruption | Use the extracted .mmdb, verify its checksum, and redeploy. |
| Every user is the load balancer | Proxy address used as client address | Configure trusted proxy CIDRs and parse the rewritten header. |
| Users choose any country | Untrusted forwarding header accepted | Ignore forwarding headers from untrusted peers. |
| IPv6 failures | Malformed notation or zone ID | Validate and canonicalize IPv6; reject zone IDs. |
| Hosted timeout | No timeout or provider outage | Set connect and total timeouts, return unknown, and retry transient failures only. |
| Wrong city | VPN, mobile network, proxy, or estimation error | Use the radius and fall back to country or region. |
9. Performance, reliability, and cost
A local lookup avoids remote latency but still incurs file access; benchmark with your own workload. Reuse readers in workers, cache normalized addresses, and align cache TTL with your privacy policy. Hosted calls consume quota and can fail independently of your application, so record latency, unknown results, provider status, database age, and cache hits.
Budget for database licensing or provider plans, update bandwidth, storage, and monitoring. A smaller country database is appropriate when city and coordinates are unnecessary. Do not silently keep using a stale database after an update failure.
10. Or skip the browser setup
If your workflow also needs a rendered page image after deciding which region to show, ScreenshotNeo provides a website screenshot API and MCP server. Your PHP code still performs the lookup; ScreenshotNeo captures the resulting URL.
Cookie and consent banners, newsletter popups, and chat widgets are removed before capture. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the verdict and billing. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.
See the ScreenshotNeo API docs for options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
Plans include 1,000 screenshots per month free with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.
FAQ
Can PHP find an exact street address from an IP?
No. IP data is approximate and cannot identify a household, individual, or street address.
Should I choose GeoLite2 or GeoIP2 City?
Choose according to licensing terms and required fields, then verify current coverage and update terms with MaxMind.
Is a city result safe for access control?
No. VPNs, proxies, mobile networks, and estimation error make city data unsuitable as sole authorization evidence.
How should I handle an unknown address?
Return an explicit unknown value, continue with a safe default, and record a metric. Do not guess from language, hostname, or a previous request.


