So based on the tags I guess you are trying to do this at PHP level.
I may add it's not your only option, there are others namely:
- Firewall (CSF is perfect for this)
- ModSecurity
- htaccess
So the PHP way
The logic is essentially just looking at the user IP, determining a country and then using a IF statement to see if that users country is allowed (if yes do something, deny)
We will use the free MaxMind (GeoLite2 City) IP database to determine the user's origin country.
<?php
// MaxMind Setup
require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;
$db =new Reader('GeoLite2-City.mmdb');
$client_ip=$db->city($_SERVER['REMOTE_ADDR']);
$client_country=$client_ip->country->isoCode;
// Specification of allowed_countries
$allowed_countries=array("US","CA");
// Blocking Logic
if(!in_array($client_country,$allowed_countries)) {
header("HTTP/1.0 403 Forbidden");
echo "<h1>Access Forbidden!</h1>";
echo "<p>You are accessing from $client_country which is forbidden.</p>";
exit();
}
?>
<html>
<head>
<title>Example Success</title>
</head>
<body>
<h1>Welcome</h1>
<p>You have access to this website.</p>
</body>
</html>
So all you need to do is first install the GeoIP2-php API which this script relies on- to do this execute the following commands (as outlined here):
curl -sS https://getcomposer.org/installer | php
php composer.phar require geoip2/geoip2:~2.0
You will now need to download the IP database to the website directory where the script will run.
wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.tar.gz && gunzip GeoLite2-City.tar.gz
- You then want to move the
GeoLite2-City.mmdb
from the folder to the directory of the server. Ensure you, of course, check the licenses, readme and copyright notice that comes with it.
Once you have all this done- the script will work, you can modify it as needed however currently if the user accesses from a country not specified in the $allowed_countries=array("US","CA");
line (array) then they will be greeted with a 403 Forbidden page.
If the country is specified then anything below the initial PHP section will be displayed- in this case <h1>Welcome</h1>
page- how you implement this PHP script is dependent on your specific circumstance.