Blocking Website Access by Country with PHP and IpToCountryAn easy method for blocking website access for specific countries or IP ranges. Just a few lines of code and virtually no server load.
A while back one of my websites came under a massive attack receiving an additional 1000+ hits per day, all malicious construction and all from one particular country. Since I was fast approaching my allocated bandwidth limit I had to take action to stop them accessing the site, and fast!
I decided to take drastic action to block the entire country from accessing my site; I have had no legitimate visits from that country and can probably do without it. Whilst reading about blocking a country (or extension) everybody talks about how difficult and time-consuming it would be to use .htaccess and block IP address ranges manually.
I have found an easy method for blocking a country, it only takes a few lines of code and has virtually no server load, so read on and I'll tell you.
Blocking website access on a per-country basis works like this:
Goto http://www.phptutorial.info/iptocountry/the_script.html for a look at "country identification without databases." Download the complete database (~540k) and extract it to a folder on your website. It will create a folder called 'ip_files'.
Next, use this bit of PHP at the top of each of your pages. (Code provided on phptutorial.info)
if ($_SERVER['HTTP_X_FORWARDED_FOR'])
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
else
$ip = $_SERVER['REMOTE_ADDR'];
$two_letter_country_code=iptocountry($ip);
function iptocountry($ip)
{
$numbers = preg_split( "/./", $ip);
include("ip_files/".$numbers[0].".php");
$code=($numbers[0] * 16777216) + ($numbers[1] * 65536) + ($numbers[2] * 256) + ($numbers[3]);
foreach($ranges as $key => $value)
{
if($key<=$code)
{
if($ranges[$key][0]>=$code)
{
$country=$ranges[$key][1];break;
}
}
}
if ($country=="")
{
$country="unknown";
}
return $country;
}
Then, add this little blocking script at the end of the code above:
if ($two_letter_country_code=="US")
die();
You should replace US with the two letter country code for the country you are trying to block.
I have taken this a bit further on mine, in that, I check for a valid session, and if not found, run all the checks and create a session. This prevents the script from running every page load - just when a new visitor connects.
<?php
session_start();
if (!isset($_SESSION['FirstVisit']))
{
if ($two_letter_country_code=="US")
die();
else
$_SESSION['FirstVisit'] = 1;
}
?>p
Of course, this blocking website access script isn't a perfect solution and will only protect your PHP pages, but in an emergency?
Note, you can find a full list of country codes listed in countries.php
within ip_files folder of the zip file.