Guide

Block or Redirect Visitors by Country in PHP

Check the country on your server, with one cached IP lookup, and decide what each visitor gets.

To block or redirect by country, look up the visitor's IP address on your server, cache the answer, and apply your rules before PHP sends any output. The file below does that with no Composer packages. If a lookup fails, it lets the visitor through, and you can change that.

PHP

PHP 8.1 or later, with the curl extension. Also in Node.js.

1Read the visitor's address, and trust only your own proxy.

REMOTE_ADDR is usually the visitor's address, unless a proxy or load balancer sits in front. Then it can be the proxy's, which usually passes the visitor's address in X-Forwarded-For. Some web servers already put the real address back into REMOTE_ADDR, so check yours. Anyone can send that header, so set TRUSTED_PROXIES only to the number of proxies you control, and count from the right. If a visitor can reach your site without going through the proxy, they can fake it. On a hosting platform or CDN, check its documentation for the header it sets.

PHP
// How many reverse proxies of YOUR OWN append to X-Forwarded-For before a
// request reaches PHP. 0 means REMOTE_ADDR is already the visitor.
define('TRUSTED_PROXIES', (int) (getenv('TRUSTED_PROXIES') ?: 0));

function client_ip(): ?string
{
    $ip = $_SERVER['REMOTE_ADDR'] ?? '';
    if (TRUSTED_PROXIES > 0) {
        // Count from the right: anything further left can be typed in by the visitor.
        $chain = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '');
        $forwarded = trim($chain[count($chain) - TRUSTED_PROXIES] ?? '');
        $ip = $forwarded !== '' ? $forwarded : $ip;
    }
    // Some load balancers add a port: 203.0.113.7:5555 or [2001:db8::1]:5555.
    $ip = preg_replace(['/^\[(.*)\](:\d+)?$/', '/^([\d.]+):\d+$/'], '$1', $ip);
    $ip = preg_replace('/^::ffff:(?=\d+\.)/i', '', $ip); // IPv4-mapped
    // Private and local addresses have no country, so don't spend a lookup on them.
    $flags = FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE;
    return filter_var($ip, FILTER_VALIDATE_IP, $flags) ?: null;
}

2Look up the country with one HTTPS request.

Create a free key (2,000 lookups a day, no card) and keep it on your server, in an environment variable. On PHP-FPM, set the file's environment variables in your pool configuration (for example env[IPWHO_API_KEY]), because it clears them by default. get=geoLocation asks for the location block only. Here is a request and an example reply:

Request
curl -H "Authorization: Bearer $IPWHO_API_KEY" \
  "https://api.ipwho.org/ip/91.0.0.1?get=geoLocation"
JSON
{
  "success": true,
  "data": {
    "geoLocation": {
      "accuracy_radius": 5,
      "capital": "Berlin",
      "city": "Düsseldorf",
      "continent": "Europe",
      "continentCode": "EU",
      "country": "Germany",
      "countryCode": "DE",
      "dial_code": "+49",
      "is_in_eu": true,
      "latitude": 51.2294,
      "longitude": 6.7855,
      "postal_Code": "40211",
      "region": "North Rhine-Westphalia",
      "regionCode": "NW"
    }
  }
}

Your rules need only data.geoLocation.countryCode. It can be null. A private or reserved address gets HTTP 404. The code gives the request 1.5 seconds, so a slow lookup can't hang a page for longer than that. This is the second half of the country_for() function, which makes the request and saves the answer. The first half, in step 3, checks the cache.

PHP
    $curl = curl_init("https://api.ipwho.org/ip/{$ip}?get=geoLocation");
    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT_MS => 1000,
        CURLOPT_TIMEOUT_MS => 1500,
        CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('IPWHO_API_KEY')],
        CURLOPT_USERAGENT => 'country-gate/1.0',
    ]);
    $body = curl_exec($curl);
    $status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
    $json = is_string($body) ? json_decode($body, true) : null;

    $country = null;
    $ttl = 60; // after a failure, try this address again soon
    if ($status === 200 && ($json['success'] ?? false)) {
        $code = $json['data']['geoLocation']['countryCode'] ?? null;
        $country = is_string($code) ? $code : null;
        $ttl = 86400;
    } elseif ($status === 404) {
        $ttl = 86400; // reserved or unrecognised address
    } else {
        error_log("country-gate: lookup failed (HTTP {$status})");
        if ($status === 429) {
            cache_write($pause, ['expires' => time() + 60]);
        }
    }
    cache_write($file, ['country' => $country, 'expires' => time() + $ttl]);
    return $country;
}

3Cache each answer, so repeat requests don't use lookups.

PHP starts fresh on every request, so the cache is a folder of small files. It keeps a successful answer for 24 hours and a failed one for a minute, and stops calling for a minute after an HTTP 429 (a rate or daily limit). Our API terms let you cache results inside your own application for a reasonable time, as long as you don't resell or expose them.

Keep the folder outside your web root, and delete old files from time to time. For a busy site or several servers, use a shared store such as Redis. Bots have IP addresses too, so count their traffic when you pick a plan.

PHP
// Keep the cache outside your web root, in a folder only your site can write to.
define('CACHE_DIR', getenv('COUNTRY_CACHE_DIR') ?: dirname(__DIR__) . '/country-cache');

function cache_write(string $file, array $entry): void
{
    if (!is_dir(CACHE_DIR) && !@mkdir(CACHE_DIR, 0700, true) && !is_dir(CACHE_DIR)) {
        error_log('country-gate: cannot create the cache folder');
        return;
    }
    // Write a temporary file, then rename it, so no request reads half a file.
    $temp = $file . '.' . bin2hex(random_bytes(6));
    if (@file_put_contents($temp, json_encode($entry)) === false || !@rename($temp, $file)) {
        error_log('country-gate: cannot write to the cache folder');
    }
}

function cache_read(string $file): ?array
{
    $entry = is_file($file) ? json_decode((string) file_get_contents($file), true) : null;
    return is_array($entry) && ($entry['expires'] ?? 0) > time() ? $entry : null;
}

// Returns a country code, or null when we don't know.
function country_for(string $ip): ?string
{
    $file = CACHE_DIR . '/' . hash('sha256', $ip) . '.json';
    if ($hit = cache_read($file)) {
        return $hit['country'];
    }
    // After an HTTP 429 we stop calling the API for a minute.
    $pause = CACHE_DIR . '/pause.json';
    if (cache_read($pause)) {
        return null;
    }

4Block, redirect or let through, and decide what “unknown” means.

A blocked visitor gets HTTP 403. If you block for a legal reason, HTTP 451 says so. A redirect uses 302, because browsers can remember a 301. Only the home page redirects, so deep links still work, and a link to /?stay=1 lets a visitor stay.

If there's no country, because a lookup failed or the reply has none, this code lets the visitor through (“fails open”). For a strict rule you can block unknown visitors instead, but then a failed lookup blocks a real visitor.

PHP
// Your rules, as two-letter country codes. Replace the examples.
define('BLOCKED_COUNTRIES', array_map(
    fn (string $code): string => strtoupper(trim($code)),
    explode(',', getenv('BLOCKED_COUNTRIES') ?: 'AQ')
));
const HOME_REDIRECTS = ['DE' => '/de/', 'FR' => '/fr/'];

function apply_country_rules(): ?string
{
    if (!getenv('IPWHO_API_KEY')) {
        error_log('country-gate: set IPWHO_API_KEY');
        return null;
    }
    $ip = client_ip();
    $country = $ip === null ? null : country_for($ip);

    // The answer depends on who is asking, so a shared cache must not reuse it.
    header('Cache-Control: private, no-store');
    if (isset($_GET['stay'])) {
        setcookie('region_choice', 'stay', [
            'expires' => time() + 31536000, 'path' => '/', 'samesite' => 'Lax',
        ]);
    }
    if ($country === null) {
        return null; // unknown: fail open
    }
    if (in_array($country, BLOCKED_COUNTRIES, true)) {
        http_response_code(403);
        header('Content-Type: text/plain; charset=utf-8');
        exit("Sorry, this site is not available in your country.\n");
    }
    // Redirect the home page only, and respect a visitor who chose to stay.
    $path = explode('?', $_SERVER['REQUEST_URI'] ?? '/', 2)[0];
    $stay = isset($_GET['stay']) || ($_COOKIE['region_choice'] ?? '') === 'stay';
    if ($path === '/' && !$stay && isset(HOME_REDIRECTS[$country])) {
        header('Location: ' . HOME_REDIRECTS[$country], true, 302); // temporary, never 301
        exit;
    }
    return $country;
}

$visitorCountry = apply_country_rules();

5Add the full file and test all three outcomes.

Save this as lib/country-gate.php, next to your public folder, and replace the example rules with your own.

lib/country-gate.php
<?php
// country-gate.php: block or redirect visitors by country with the IPWho API.
// PHP 8.1 or later with the curl extension. Require it before any output.
declare(strict_types=1);

// Your rules, as two-letter country codes. Replace the examples.
define('BLOCKED_COUNTRIES', array_map(
    fn (string $code): string => strtoupper(trim($code)),
    explode(',', getenv('BLOCKED_COUNTRIES') ?: 'AQ')
));
const HOME_REDIRECTS = ['DE' => '/de/', 'FR' => '/fr/'];

// How many reverse proxies of YOUR OWN append to X-Forwarded-For before a
// request reaches PHP. 0 means REMOTE_ADDR is already the visitor.
define('TRUSTED_PROXIES', (int) (getenv('TRUSTED_PROXIES') ?: 0));

// Keep the cache outside your web root, in a folder only your site can write to.
define('CACHE_DIR', getenv('COUNTRY_CACHE_DIR') ?: dirname(__DIR__) . '/country-cache');

function client_ip(): ?string
{
    $ip = $_SERVER['REMOTE_ADDR'] ?? '';
    if (TRUSTED_PROXIES > 0) {
        // Count from the right: anything further left can be typed in by the visitor.
        $chain = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '');
        $forwarded = trim($chain[count($chain) - TRUSTED_PROXIES] ?? '');
        $ip = $forwarded !== '' ? $forwarded : $ip;
    }
    // Some load balancers add a port: 203.0.113.7:5555 or [2001:db8::1]:5555.
    $ip = preg_replace(['/^\[(.*)\](:\d+)?$/', '/^([\d.]+):\d+$/'], '$1', $ip);
    $ip = preg_replace('/^::ffff:(?=\d+\.)/i', '', $ip); // IPv4-mapped
    // Private and local addresses have no country, so don't spend a lookup on them.
    $flags = FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE;
    return filter_var($ip, FILTER_VALIDATE_IP, $flags) ?: null;
}

function cache_write(string $file, array $entry): void
{
    if (!is_dir(CACHE_DIR) && !@mkdir(CACHE_DIR, 0700, true) && !is_dir(CACHE_DIR)) {
        error_log('country-gate: cannot create the cache folder');
        return;
    }
    // Write a temporary file, then rename it, so no request reads half a file.
    $temp = $file . '.' . bin2hex(random_bytes(6));
    if (@file_put_contents($temp, json_encode($entry)) === false || !@rename($temp, $file)) {
        error_log('country-gate: cannot write to the cache folder');
    }
}

function cache_read(string $file): ?array
{
    $entry = is_file($file) ? json_decode((string) file_get_contents($file), true) : null;
    return is_array($entry) && ($entry['expires'] ?? 0) > time() ? $entry : null;
}

// Returns a country code, or null when we don't know.
function country_for(string $ip): ?string
{
    $file = CACHE_DIR . '/' . hash('sha256', $ip) . '.json';
    if ($hit = cache_read($file)) {
        return $hit['country'];
    }
    // After an HTTP 429 we stop calling the API for a minute.
    $pause = CACHE_DIR . '/pause.json';
    if (cache_read($pause)) {
        return null;
    }

    $curl = curl_init("https://api.ipwho.org/ip/{$ip}?get=geoLocation");
    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT_MS => 1000,
        CURLOPT_TIMEOUT_MS => 1500,
        CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('IPWHO_API_KEY')],
        CURLOPT_USERAGENT => 'country-gate/1.0',
    ]);
    $body = curl_exec($curl);
    $status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
    $json = is_string($body) ? json_decode($body, true) : null;

    $country = null;
    $ttl = 60; // after a failure, try this address again soon
    if ($status === 200 && ($json['success'] ?? false)) {
        $code = $json['data']['geoLocation']['countryCode'] ?? null;
        $country = is_string($code) ? $code : null;
        $ttl = 86400;
    } elseif ($status === 404) {
        $ttl = 86400; // reserved or unrecognised address
    } else {
        error_log("country-gate: lookup failed (HTTP {$status})");
        if ($status === 429) {
            cache_write($pause, ['expires' => time() + 60]);
        }
    }
    cache_write($file, ['country' => $country, 'expires' => time() + $ttl]);
    return $country;
}

function apply_country_rules(): ?string
{
    if (!getenv('IPWHO_API_KEY')) {
        error_log('country-gate: set IPWHO_API_KEY');
        return null;
    }
    $ip = client_ip();
    $country = $ip === null ? null : country_for($ip);

    // The answer depends on who is asking, so a shared cache must not reuse it.
    header('Cache-Control: private, no-store');
    if (isset($_GET['stay'])) {
        setcookie('region_choice', 'stay', [
            'expires' => time() + 31536000, 'path' => '/', 'samesite' => 'Lax',
        ]);
    }
    if ($country === null) {
        return null; // unknown: fail open
    }
    if (in_array($country, BLOCKED_COUNTRIES, true)) {
        http_response_code(403);
        header('Content-Type: text/plain; charset=utf-8');
        exit("Sorry, this site is not available in your country.\n");
    }
    // Redirect the home page only, and respect a visitor who chose to stay.
    $path = explode('?', $_SERVER['REQUEST_URI'] ?? '/', 2)[0];
    $stay = isset($_GET['stay']) || ($_COOKIE['region_choice'] ?? '') === 'stay';
    if ($path === '/' && !$stay && isset(HOME_REDIRECTS[$country])) {
        header('Location: ' . HOME_REDIRECTS[$country], true, 302); // temporary, never 301
        exit;
    }
    return $country;
}

$visitorCountry = apply_country_rules();

Require it at the top of each page you want to guard, before any output. This is the test page, public/index.php:

public/index.php
<?php
require __DIR__ . '/../lib/country-gate.php';
echo "Hello. Country: " . ($visitorCountry ?? "unknown") . "\n";
Run
# Terminal 1. TRUSTED_PROXIES=1 and BLOCKED_COUNTRIES=JP are for this test.
IPWHO_API_KEY=sk.xxx TRUSTED_PROXIES=1 BLOCKED_COUNTRIES=JP php -S localhost:8000 -t public
Test and output
# Terminal 2. The header stands in for your proxy.
$ curl -s -w '[%{http_code}] %{redirect_url}\n' -H 'X-Forwarded-For: 8.8.8.8' http://localhost:8000/
Hello. Country: US
[200]

$ curl -s -w '[%{http_code}] %{redirect_url}\n' -H 'X-Forwarded-For: 91.0.0.1' http://localhost:8000/
[302] http://localhost:8000/de/

$ curl -s -w '[%{http_code}] %{redirect_url}\n' -H 'X-Forwarded-For: 133.0.0.1' http://localhost:8000/
Sorry, this site is not available in your country.
[403]

PHP's built-in server is for testing only. In production, set TRUSTED_PROXIES to match your real setup, and leave it at 0 if you have no proxy.

Check these before you switch it on.

Start with a free API key

Free tier: 2,000 lookups a day, no card. Paid plans from $2.50 a month billed yearly. See the full field reference.