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

// by BlackDog 20130129
$location = ''; // where to send bad people

$range_low = ip2long("");
$range_high = ip2long("");

$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 through to, 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.


Leave a Reply

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