Block specific IP block from my website in PHP

Use ip2long() to convert dotted decimal to a real IP address. Then you can do ranges easily.

Just do ip2long() on the high and low range to get the value, then use those as constants in your code.

If you're familiar with subnet masking, you can do it like this:

// Deny 10.12.*.*
$network = ip2long("10.12.0.0");
$mask = ip2long("255.255.0.0");
$ip = ip2long($_SERVER['REMOTE_ADDR']);
if (($network & $mask) == ($ip & $mask)) {
  die("Unauthorized");
}

Or if you're familiar with this format 10.12.0.0/16:

// Deny 10.12.*.*
$network = ip2long("10.12.0.0");
$prefix = 16;
$ip = ip2long($_SERVER['REMOTE_ADDR']);
if ($network >> (32 - $prefix)) == ($ip >> (32 - $prefix)) {
  die("Unauthorized");
}

You can turn these into functions and have very manageable code, making it easy to add IP addresses and customize the ranges.


Try strpos()

if(strpos($_SERVER['REMOTE_ADDR'], "89.95") === 0)
{
    die();
}

If you notice, the === operator makes sure that the 89.95 is at the beginning of the IP address. This means that you can specify as much of the IP address as you want, and it will block no matter what numbers come after it.

For instance, all of these will be blocked:

89.95 -> 89.95.12.34, 89.95.1234.1, 89.95.1.1
89.95.6 -> 89.95.65.34, 89.95.61.1, 89.95.6987

(some of those aren't valid IP addresses though)

Tags:

Php

Ip