01/29/13
Paul Savage
tags:   ,

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 Responses to “Blocking IP ranges with PHP”

  1. Michele Michele

    Paul

    Maxmind’s DB is pretty handy when you want to do things based on countries and is available both as a web service and using a local DB.

    We’ve been using it for a variety of things for several years and they also have some support for IPv6

    Michele

  2. Fra_T Fra_T

    The 301 status code and the location header does not ensure that the content is blocked. To be sure you should add a “die” or “exit” somewhere.

    header (‘HTTP/1.1 301 Moved Permanently’);
    header (‘Location: ‘.$location);

    Secret content here

    The Secret content can be read from a client if it is programmed to do not follow the redirects.

    In PHP for example it can be done with the curl functions and the follow option set:

    curl_setopt(CURLOPT_FOLLOWLOCATION, false);

  3. Eileen Eileen

    Hi, forgive me – I’m new to this topic, but what are the reasons why you would block a range of IP addresses?

  4. Paul Savage Paul Savage

    Thanks for popping by Eileen. If you are, for example, are having issues with spammers coming from a certain IP it might be a good idea to block the range so that all other IPs on that network are also blocked. This can save you time rather than blocking them individually.

Leave a Reply