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/ */
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;
}
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
);
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
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
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.