Get the visitor’s connection IP from $_SERVER['REMOTE_ADDR'], validate it with PHP’s FILTER_VALIDATE_IP, then use a GeoIP2 database or authenticated web service to look up the country. The result is an estimate based on the provider’s IP data—not proof of a person’s residence or precise location.
1. Read and validate the connection IP
PHP exposes the address from which a request reaches the web server as $_SERVER['REMOTE_ADDR']. The web server supplies entries in $_SERVER, and PHP notes that not every server is guaranteed to provide every entry, so check that the value exists and is a string before using it. See PHP’s documentation for $_SERVER.
<?php
$ip = $_SERVER['REMOTE_ADDR'] ?? null;
if (!is_string($ip) || filter_var($ip, FILTER_VALIDATE_IP) === false) {
http_response_code(400);
exit('A valid IP address is required.');
}
FILTER_VALIDATE_IP accepts valid IPv4 or IPv6 addresses. PHP also provides flags to limit validation to IPv4 or IPv6, or to reject reserved and private ranges. Choose those flags to fit the application; a syntactically valid IP is not necessarily globally routable. See PHP’s validation filter documentation.
When the site is behind a proxy
Behind a reverse proxy or load balancer, REMOTE_ADDR may identify the proxy that connected to the application rather than the original visitor. Do not substitute an arbitrary X-Forwarded-For value: clients can send such headers themselves. Use a forwarded address only when your own trusted proxy infrastructure is configured to set and sanitize it, following the rules for that deployment. PHP’s server-variable documentation does not establish a universal trusted-proxy algorithm.
#1 Best Overall
2. Choose a GeoIP2 lookup source
PHP’s legacy GeoIP extension does not read MaxMind’s current GeoIP2 databases; PHP documents it as supporting only legacy GeoIP database files. For current GeoIP2 data, use MaxMind’s GeoIP2 PHP client with either a local database or a hosted service.
| Option | How it works | Operational trade-off |
|---|---|---|
| Local database | The application reads a downloaded GeoIP2 database file. | No provider HTTP request for each lookup, but you must store and update the database and comply with the selected database’s terms. |
| Hosted country service | The application sends the IP to an authenticated provider endpoint. | No local database file to maintain, but each lookup depends on network and service availability, and credentials must be managed securely. |
MaxMind documents a database update program and requires an account ID and license key for its hosted service. Check the terms and update requirements for the specific database or service you select; these can vary. Its country service returns less data than its City Plus and Insights endpoints, so a country-only task does not require a city-level lookup.
Rank #2
3. Look up a country with a local database
Install MaxMind’s PHP client using Composer, obtain a compatible country database, and pass its path to GeoIp2DatabaseReader. The returned country record exposes fields such as the ISO country code and country name.
<?php
require __DIR__ . '/vendor/autoload.php';
use GeoIp2DatabaseReader;
$ip = $_SERVER['REMOTE_ADDR'] ?? null;
if (!is_string($ip) || filter_var($ip, FILTER_VALIDATE_IP) === false) {
throw new InvalidArgumentException('Invalid IP address');
}
$reader = new Reader(__DIR__ . '/geoip/GeoLite2-Country.mmdb');
try {
$record = $reader->country($ip);
$countryCode = $record->country->isoCode;
$countryName = $record->country->name;
} finally {
$reader->close();
}
Use the actual path and database product you have obtained; the filename above is an example, not a guarantee about your installation. A missing address record and a corrupt database are distinct failure cases in the client, so handle lookup and database errors according to the application rather than treating every failure as “unknown country.” MaxMind’s PHP API documentation covers database-reader usage and exceptions.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →4. Look up a country with a hosted service
If you prefer not to manage a local database file, the GeoIP2 PHP client can call MaxMind’s authenticated country web service. Supply the account ID and license key obtained for the service, then call country($ip).
<?php
require __DIR__ . '/vendor/autoload.php';
use GeoIp2WebServiceClient;
$ip = $_SERVER['REMOTE_ADDR'] ?? null;
if (!is_string($ip) || filter_var($ip, FILTER_VALIDATE_IP) === false) {
throw new InvalidArgumentException('Invalid IP address');
}
$client = new Client($accountId, $licenseKey);
$record = $client->country($ip);
$countryCode = $record->country->isoCode;
$countryName = $record->country->name;
Keep credentials out of source control and make the lookup failure path explicit in your application. MaxMind’s country endpoint accepts IPv4 and IPv6, requires authorization, and requires TLS 1.2 or later. The endpoint can return JSON; the PHP client provides structured response models and exceptions. See MaxMind’s API request documentation and the PHP client documentation.
Rank #4
5. Treat the country as an estimate
MaxMind cautions: “IP geolocation is inherently imprecise. Any location provided by a GeoIP database or web service should not be used to identify a particular address or household.” A country result can be useful for localization or coarse analytics, but it does not establish a visitor’s identity, residence, or exact physical location.
If you use a service response’s latitude or longitude, MaxMind recommends considering its Accuracy Radius as an indication of uncertainty; it is not a guarantee of exactness. Do not interpret country or coordinate fields as verified location data.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

