Recently this website came under a massive spammer attack, almost all hits (200+) per day were from one particular country. Since I was approaching the bandwidth limit I had to take action to stop them accessing the site, and fast. I decided to take the drastic action to block the entire country from accessing my site; I have had not legitimate visits from that country and can probably do without. Whilst reading about blocking a country (or extension) everybody talks about how difficult and time consuming it would be using .htaccess.
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.
It 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="unkown";
}
return $country;
}
and add this little blocking script at the end of the code above:
if ($two_letter_country_code=="US") die();
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.
Of course this isn’t a perfect solution and will only protect your php pages, but in an emergency?
Note, you can find a list of country codes listed in countries.php within ip_files.













