Block or Allow access to PHP script based on remote IP and CIDR list

400px-CIDR_Address Spam…we all hate it. It is nice when things like reCaptcha and Asimet work but these Chinese have a way of bypassing those spam filters and then fill your blog or website with useless comments and fake registrations. So, how about a way to just block all ip addresses coming from a specific region from viewing your registration page or comment box? Well…find below some steps to follow to do exactly that.

Step 1:

Get a list of country or regional specific CIDR (Classless Inter-Domain Routing) IPs and store them in an accessible place (file or database). You could use the link below to get country specific CIDRs.

http://ipinfodb.com/ip_country_block.php

Step 2:

Store your CIDRs into array (you can read them from a database or something of the sort)

$cidrs = array(
  '192.168.1.20/27', 
  '192.168.0.10/32'
  );

 

Step 3:

Add or include the following function to your script

function cidr_match($ip, $range)
{
    list ($subnet, $bits) = explode('/', $range);
    $ip = ip2long($ip);
    $subnet = ip2long($subnet);
    $mask = -1 << (32 - $bits);
    $subnet &= $mask;
    return ($ip & $mask) == $subnet;
}

 

Step 4:

Get user’s IP address (remote address)

$user_ip = $_SERVER['REMOTE_ADDR'];

 

Step 5:

Compare user’s IP address against CIDRs

$validaddr = false;
foreach ($cidrs as $addr)
  if (cidr_match($user_ip, $addr)) {
    $validaddr = true;
    break;
    } 

 

Step 6:

Decide what to do with the user

if ($validaddr) {
  echo "CORRECT IP ADDRESS";
  }
else {
  echo "INCORRECT IP ADDRESS";
  }

 

Well, there you have it. You could combine this into a function that does the double loop if you like but it gets the job done. Hec…you could use this script in a myriad of ways, (not just to block people) like redirect to different language versions of your site,

Share

1 comment

Leave a Reply