PHP code example of mpge / php-country-block

1. Go to this page and download the library: Download mpge/php-country-block library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mpge / php-country-block example snippets


$blocker = CountryBlocker::block(['CA', 'US', 'CG'])
    ->using(new Ip2LocationResolver($apiKey));

if ($blocker->check()->blocked) {
    http_response_code(403);
    exit;
}



pge\CountryBlock\CountryBlocker;
use Mpge\CountryBlock\Resolver\Ip2LocationResolver;

// IP2Location.io works without a key at 1,000 lookups a day.
$blocker = CountryBlocker::block(['CA', 'US', 'CG'])
    ->using(new Ip2LocationResolver());

$decision = $blocker->check();

if ($decision->blocked) {
    http_response_code(403);
    echo 'Not available in your country.';
    exit;
}

$blocker = CountryBlocker::allow(['CA'])
    ->using(new Ip2LocationResolver($apiKey))
    ->onFailure(FailureMode::Block);

interface CountryResolver
{
    public function resolve(string $ip): ?Lookup;
}

new IpApiComResolver(allowInsecureTransport: true);   // keyless, plaintext, eyes open
new IpApiComResolver('pro-key');                      // https://pro.ip-api.com, no opt-in needed

new MaxMindResolver('/var/lib/GeoIP/GeoLite2-Country.mmdb');

$blocker = CountryBlocker::block(['RU', 'KP'])
    ->using(
        new CloudflareHeaderResolver(),                              // free, already resolved
        new MaxMindResolver('/var/lib/GeoIP/GeoLite2-Country.mmdb'), // local disk
        new Ip2LocationResolver($apiKey),                            // paid, accurate
        new IpApiCoResolver(),                                       // keyless backstop
    );

$blocker = $blocker->onResolverError(function (CountryResolver $resolver, ResolverException $e) use ($log) {
    $log->warning('Country lookup failed', ['resolver' => $resolver::class, 'error' => $e->getMessage()]);
});

$blocker = CountryBlocker::block(['CA'])
    ->using(new Ip2LocationResolver($apiKey))
    ->withCache(new FileCache('/tmp/country-block'), ttl: 86400, negativeTtl: 300);

$blocker = $blocker->trustProxies(['10.0.0.0/8', '2001:db8::/32']);

use Mpge\CountryBlock\Net\ClientIpResolver;

$blocker = $blocker->trustProxies(['10.0.0.0/8'], [ClientIpResolver::CLOUDFLARE]);

->onFailure(FailureMode::Allow)   // default: the site stays up, some traffic gets through
->onFailure(FailureMode::Block)   // sanctions, licensing, regulatory fencing

$decision = $blocker->check();

$decision->blocked;       // bool
$decision->allowed();     // bool
$decision->resolved();    // false when the verdict came from the FailureMode
$decision->countryCode;   // 'DE', or null
$decision->source;        // 'ip2location.io', 'cloudflare', ... or null
$decision->cached;        // came from the cache rather than a fresh lookup
$decision->ip;            // the address that was checked
$decision->reason;        // Reason::Listed | NotListed | Unresolved

// check.php, ountryBlocker::block(['CA', 'US', 'CG'])
    ->using(new Ip2LocationResolver($_ENV['IP2LOCATION_KEY']))
    ->withCache($psr16Cache)
    ->check();

if ($decision->blocked) {
    header('Location: /unavailable.php');
    exit;
}

final class BlockCountries
{
    public function __construct(private readonly CountryBlocker $blocker) {}

    public function handle(Request $request, Closure $next): Response
    {
        if ($this->blocker->check($request->ip())->blocked) {
            abort(403, 'Not available in your country.');
        }

        return $next($request);
    }
}

$resolver = app()->environment('local')
    ? new StaticResolver('DE')
    : new Ip2LocationResolver($apiKey);
bash
composer