19867

Blocking IP ranges with PHP

Recently I wanted to block certain ranges of IP address via PHP from visiting a website. I discovered a handy function ip2long, which can take incomplete ranges of IP addresses. Here is an example


<?php
// by BlackDog 20130129
$location = 'http://www.male.ie/'; // where to send bad people

$range_low = ip2long("100.100.100.100");
$range_high = ip2long("200.200.200.200");
// AAA.BBB.CCC.DDD

$ip = ip2long($_SERVER['REMOTE_ADDR']);
if ($ip >= $range_low && $ip <= $range_high) {
// what to do if in bad IP range
header ('HTTP/1.1 301 Moved Permanently');
header ('Location: '.$location);
}
else {
// do something else or nothing at all
}
?>

The code above will block anyone from IP ranges 100.100.100.100 through to 200.200.200.200, and will redirect them to another website .

Other ways

This is quite a quick and simple way of achieving the goal of block a range of IP addresses. Other ways would be to perhaps have a database table with a list of bad IPs, and do a query per page request to see if they are white-listed. There is also a good article about saving IP addresses to databases that’s worth reading. This code will probably have to be updated once IPv6 comes more and more popular, but for the moment only works for IPv4.

4 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>