IP geolocation in PHP
Look up the country, city, ISP and time zone of an IP address in PHP with cURL and the IPIDB API, with caching, error handling and the real client IP.
This guide shows how to look up an IP address from PHP: the country, region, city, coordinates, time zone, ISP and ASN. It uses only the cURL extension that ships with almost every PHP build, so there is nothing to install with Composer. The code works on PHP 7.4 and newer.
What you need
- An IPIDB API key. The free plan gives 1,000 lookups a day; create an account and copy the key from the dashboard.
- PHP with the
curlandjsonextensions (check withphp -m).
Keep the key out of your code. The examples read it from the environment variable IPIDB_KEY.
The first lookup
Every request goes to https://api.ipidb.com/v1/ip/{ip} with the key in the X-API-Key header. The answer is JSON with the objects location, timezone and network.
<?php $key = getenv('IPIDB_KEY'); $ip = '8.8.8.8'; $ch = curl_init('https://api.ipidb.com/v1/ip/' . rawurlencode($ip)); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_CONNECTTIMEOUT => 3, CURLOPT_TIMEOUT => 5, CURLOPT_HTTPHEADER => ['X-API-Key: ' . $key], ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); $data = json_decode((string)$body, true); if ($status === 200 && !empty($data['success'])) { printf("%s, %s (%s)\n", $data['location']['city'], $data['location']['country'], $data['network']['isp']); } else { echo 'Lookup failed: ', $data['error']['code'] ?? "HTTP $status", "\n"; }
Run it with IPIDB_KEY=your_key php lookup.php. For 8.8.8.8 it prints Mountain View, United States (Google).
A reusable function
In an application you want one function that returns an array or null, never throws on a network problem, and does not slow the page down when the API is unreachable. The short timeouts above already cap the wait at five seconds; the function below also caches answers, because the location of an address rarely changes within a day.
<?php
/**
* Look up an IP address. Returns the decoded response or null.
* Answers are cached for a day in APCu when it is available.
*/
function ipidb_lookup(string $ip): ?array
{
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
return null;
}
$cacheKey = 'ipidb:' . $ip;
if (function_exists('apcu_fetch')) {
$hit = apcu_fetch($cacheKey, $ok);
if ($ok) {
return $hit;
}
}
$ch = curl_init('https://api.ipidb.com/v1/ip/' . rawurlencode($ip));
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 2,
CURLOPT_TIMEOUT => 4,
CURLOPT_HTTPHEADER => ['X-API-Key: ' . getenv('IPIDB_KEY')],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = json_decode((string)$body, true);
if ($status !== 200 || empty($data['success'])) {
error_log('ipidb: ' . ($data['error']['code'] ?? "http $status") . " for $ip");
return null;
}
if (function_exists('apcu_store')) {
apcu_store($cacheKey, $data, 86400);
}
return $data;
}The address of the visitor
$_SERVER['REMOTE_ADDR'] is the address that opened the connection. Behind a load balancer or a CDN that is the proxy, not the visitor. Only trust a forwarded header when the request really came from your proxy; otherwise anyone can send a fake X-Forwarded-For.
<?php function client_ip(array $trustedProxies = ['127.0.0.1']): string { $remote = $_SERVER['REMOTE_ADDR'] ?? ''; if (!in_array($remote, $trustedProxies, true)) { return $remote; } // the right-most address that is not one of our proxies is the client $chain = array_map('trim', explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '')); foreach (array_reverse($chain) as $ip) { if (filter_var($ip, FILTER_VALIDATE_IP) && !in_array($ip, $trustedProxies, true)) { return $ip; } } return $remote; } require __DIR__ . '/ipidb.php'; $geo = ipidb_lookup(client_ip()); $country = $geo['location']['country_code'] ?? 'unknown';
If you use Cloudflare, it sends the visitor address in CF-Connecting-IP; trust it only for requests that come from Cloudflare's published ranges.
Only the fields you need
Add ?fields= with a comma-separated list of paths to make the answer smaller. For a country switcher this is enough:
https://api.ipidb.com/v1/ip/8.8.8.8?fields=location.country_code,timezone.id
Handling errors and limits
Errors come back as JSON with success: false and an error.code. The ones to plan for:
invalid_key(401): the key is wrong or was revoked.rate_limited(429): more requests per second than the plan allows. Wait one second and retry.quota_exceeded(429): the daily or monthly quota is used up;X-Quota-Resetsays when it resets.
The headers X-Quota-Limit and X-Quota-Remaining show how much is left, so you can log a warning before the quota runs out. The full list is in the error reference.
Next steps
Paid plans add security flags (VPN, proxy, Tor, hosting), the abuse contact, reverse DNS and the IP range to the same response. The tutorial on detecting VPN and proxy logins builds on the function above.
Related
- API documentation: every endpoint, field and error code
- IPIDB APIs: IP data, blacklist and MAC vendor lookups
- Pricing: the free plan and what paid plans add
- IP geolocation in Python
- IP geolocation in Node.js
- IP geolocation in Go
- Block countries in nginx with an MMDB database
- Detect VPN and proxy logins