How to block website for all countries except US and Canada

5,285

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:

  1. Firewall (CSF is perfect for this)
  2. ModSecurity
  3. 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):

  1. curl -sS https://getcomposer.org/installer | php
  2. 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.

  1. wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.tar.gz && gunzip GeoLite2-City.tar.gz
  2. 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.

Share:
5,285

Related videos on Youtube

Dileep Kumar
Author by

Dileep Kumar

Updated on September 18, 2022

Comments

  • Dileep Kumar
    Dileep Kumar almost 2 years

    I have a website which is only for US and Canada visitors. I don't want to make it visible to other visitors.

    I want to use Geo targeting solution but I have a amazon hosting it did return current user IP Address so is there any way to getting user current location or if we can do it with another way?