October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
GeoLite2

How to Geolocate an IP Address with PHP

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

PHP cannot determine an IP address’s location by itself. You need a geolocation data source: either a local MaxMind GeoIP2 database read with its maintained PHP package, or a hosted geolocation service called through an official client. Validate the IP, handle missing records and service failures, and treat the result as an estimate—not GPS or a street address.

What PHP can—and cannot—tell you from an IP address

An IP geolocation lookup maps a network address to an estimated geographic area using a provider’s database or service. PHP supplies the request handling and integration; it does not contain a built-in, current map of IP addresses. MaxMind describes IP geolocation as inherently imprecise. Its current accuracy guidance, accessed in 2026, 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. Those are MaxMind estimates, not guarantees for every provider, address, or location.

A returned city, postal code, or coordinate is not proof of where a person is. VPNs, proxies, hosting networks, mobile carriers, ISP address allocation, and privacy opt-outs can all make the observed IP a poor indicator of an end user’s location. MaxMind cautions that IP data is never precise enough to identify or locate a specific household, individual, or street address, and that a coordinate should not be assumed to be the center of the relevant area. Use country or broad region for low-risk personalization; do not use IP lookup as GPS, identity verification, or proof of physical presence.

Choose a local database or a hosted service

Approach How it works Operational trade-off
Local database Install MaxMind’s GeoIP2 PHP package and read a downloaded GeoIP2 or GeoLite2 MMDB file with GeoIp2DatabaseReader. A lookup avoids a per-request network call, but you must obtain and license the database, keep it updated, provide disk space, and monitor update failures.
Hosted API Call a provider’s web service using its official PHP client or supported integration. The provider manages its data updates, while your application depends on credentials, outbound network access, service availability, and any applicable quota or rate limits.

Choose based on freshness and update work, whether the queried address can leave your infrastructure, acceptable lookup latency, availability requirements, and provider features or cost. Public IPv4 and IPv6 coverage is broad, but accuracy varies by region. Confirm current licensing, pricing, quotas, and update terms directly with the provider before deploying; those terms are not specified here.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use MaxMind GeoIP2 locally in PHP

Install the package and provide a database

Use Composer to add MaxMind’s maintained PHP integration, then make a compatible GeoIP2 or GeoLite2 MMDB database available to the application. The following command installs the package; commit the resulting dependency lock file so deployments use pinned versions.

composer require geoip2/geoip2

Place the database at a deployment-managed path such as /srv/app/data/GeoIP2-City.mmdb, or change the path below to match your installation. The exact fields available depend on the database product you selected. A city database may provide city and location fields; a country-focused database should not be assumed to contain them.

Validate and look up an IPv4 or IPv6 address

This example accepts the IP as a function argument, validates either address family, reads country, city, and coordinates when present, and handles both an unlisted address and a bad database. It always closes the reader.

<?php

require __DIR__ . '/vendor/autoload.php';

use GeoIp2DatabaseReader;
use GeoIp2ExceptionAddressNotFoundException;
use GeoIp2ExceptionInvalidDatabaseException;

function geolocateIp(string $ip): ?array
{
    if (filter_var($ip, FILTER_VALIDATE_IP) === false) {
        throw new InvalidArgumentException('Invalid IP address.');
    }

    $reader = new Reader(__DIR__ . '/data/GeoIP2-City.mmdb');

    try {
        $record = $reader->city($ip);

        return [
            'country' => $record->country->isoCode,
            'city' => $record->city->name,
            'latitude' => $record->location->latitude,
            'longitude' => $record->location->longitude,
        ];
    } catch (AddressNotFoundException $e) {
        // The database has no record for this address.
        return null;
    } finally {
        $reader->close();
    }
}

try {
    $location = geolocateIp('2001:4860:4860::8888');
    var_export($location);
} catch (InvalidArgumentException $e) {
    http_response_code(400);
    echo 'Please supply a valid IPv4 or IPv6 address.';
} catch (InvalidDatabaseException $e) {
    error_log('The geolocation database is invalid or corrupt.');
    http_response_code(500);
    echo 'Location lookup is temporarily unavailable.';
}

In a web application, return an appropriate response rather than exposing filesystem paths or exception details to the visitor. Also decide how your application should behave when a lookup returns null: for example, skip location-based personalization or use a neutral default rather than treating the address as an error.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use the actual client IP carefully

Do not blindly use HTTP_X_FORWARDED_FOR or another forwarded header as the visitor’s address. A client can supply spoofed values unless your deployment is configured to trust only known reverse proxies and to interpret their forwarding headers correctly. Determine the client IP using your web server or framework’s trusted-proxy configuration, then pass that validated address to the lookup function. If the application is directly exposed without a proxy, the connection’s remote address may be available through the server environment, but deployment topology matters.

Call a hosted geolocation service instead

A hosted service is useful when you do not want to distribute and refresh a local database. MaxMind documents a web-service client alongside its database-reader approach and recommends its official client libraries. IPinfo’s official PHP library requires an API token and documents fields including city, region, country, postal code, latitude, and longitude.

Use the provider’s current official PHP client rather than inventing a URL or response format. Read the IP from the trusted source described above, validate it with filter_var($ip, FILTER_VALIDATE_IP), keep API credentials out of source control, and configure an explicit timeout and error handling according to that client’s documentation. Treat authentication failures, timeouts, network errors, quota exhaustion, and rate limits as service errors distinct from “no record.” Avoid logging tokens or unnecessarily retaining queried IP addresses.

MaxMind’s web-service guidance accepts IPv4 and IPv6, recommends canonical IPv6 notation, rejects IPv6 zone identifiers, and supports me to look up the address of the querying client. Use that special value only where it matches your use case; for a visitor lookup, pass the visitor’s trusted IP rather than assuming the PHP server’s outbound address represents them.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Handle uncertainty and data safely

  • Use the least precise field that meets the need. Country or broad region is generally more reliable than city or coordinates.
  • Represent missing data explicitly. A database may not have a record, or the chosen product may not include a requested field. Avoid converting missing values into a misleading location.
  • Do not infer exact physical presence. VPNs, proxies, mobile networks, hosting providers, and privacy choices can shift or obscure the apparent network location.
  • Review privacy obligations. An IP address and a derived location can be sensitive in context. Collect and retain only what the application needs, and apply the rules relevant to your users and jurisdiction.
  • Keep a local database maintained. Automate authorized downloads and updates, monitor freshness, and test that a failed update does not silently leave the application using a corrupt file.
  • Plan hosted-service failure behavior. Decide what the application does on timeout, provider outage, authentication failure, or quota exhaustion; location should not become a single point of failure unless the product genuinely requires it.

Troubleshooting common PHP geolocation failures

Composer cannot load the reader class

Confirm that Composer installed the GeoIP2 package, that the application includes vendor/autoload.php, and that the deployment’s dependency installation includes the locked package. Do not rely on a package installed only on a developer’s machine.

The lookup says the address was not found

The address may be absent from the selected database. Handle AddressNotFoundException as a missing result and provide a neutral application fallback. Do not present it as proof that the IP is invalid; validate syntax separately.

The database cannot be opened or is invalid

Check the configured path, the PHP process’s read permissions, and whether the deployed file is the correct MMDB database and was downloaded intact. An invalid or corrupt database can raise an invalid-database exception. Restore a known-good authorized copy and investigate the update process rather than suppressing the error.

IPv6 addresses fail while IPv4 works

Ensure validation and the selected provider/database support IPv6, and preserve the canonical address rather than adding a zone ID. MaxMind’s web-service guidance accepts both address families and rejects zone identifiers. Check whether the client or proxy layer is altering the address before lookup.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The result points to the wrong city or country

First verify that the application looked up the correct client IP and did not trust a spoofed forwarded header. Then consider VPN or proxy use, mobile carrier routing, ISP allocation, database age, and regional accuracy. A city-level mismatch is possible even when the broad region is useful; do not use coordinates as an address.

The hosted request times out or is rejected

Check outbound connectivity, credentials, provider-specific input requirements, configured timeouts, quota, and rate limits. Distinguish a provider error from a valid response with no location record, and avoid exposing provider response details to end users.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability, and cost considerations

A local read avoids an API network round trip for each lookup, but its practical speed depends on the host, database, and application workload; no specific latency is guaranteed. Reuse or manage readers appropriately for the lifetime and concurrency model of your PHP application, and benchmark your own deployment before optimizing. Ensure database updates are atomic or otherwise cannot expose a partially written file.

A hosted API shifts database distribution and freshness work to the provider, but adds network latency and a dependency on credentials, quotas, and service availability. Consider caching only where the provider’s terms and your privacy policy allow it, and set retention according to the sensitivity and purpose of the data. Compare total cost and operational effort using current provider terms rather than assuming either approach is universally cheaper.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not confuse GeoIP2 with PHP’s legacy GeoIP extension

PHP’s built-in GeoIP extension is for legacy GeoIP database files and does not support MaxMind’s current GeoIP2 databases. For a new GeoIP2 implementation, use the maintained provider package and pin its Composer dependency versions; do not choose the legacy extension expecting it to read an MMDB GeoIP2 database.

Or skip the browser setup

ScreenshotNeo is a website screenshot API, not an IP geolocation service, so it does not replace the PHP lookup above. If your adjacent task is capturing a rendered webpage rather than locating an IP, one GET request returns an image or PDF. See the ScreenshotNeo API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Before capture, it accepts cookie or consent banners like a visitor and removes 60+ known consent platforms, newsletter popups, and chat widgets; each cleanup step can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers report the page verdict and billing status. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots. Learn about ScreenshotNeo or sign up for 1,000 free screenshots a month with no card.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can IP geolocation identify a person’s home address?

No. An IP lookup cannot reliably identify a person, household, or street address.

Does a PHP IP lookup return the visitor’s exact location?

No. It returns an estimate of the network’s likely area, and the result may reflect a VPN, proxy, mobile network, or ISP allocation instead of the end user’s location.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.