Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block specific IP block from my website in PHP

Tags:

php

ip

I'd like, for example, block every IP from base 89.95 (89.95..). I don't have .htaccess files on my server, so I'll have to do it with PHP.

if ($_SERVER['REMOTE_ADDR'] == "89.95.25.37") die();

Would block specific IP. How can I block entire IP blocks?

like image 273
iTayb Avatar asked May 19 '10 22:05

iTayb


People also ask

How do I block an IP address from my website?

Head to the “Security” section and find the “IP Address Deny Manager”, then enter a specific IP address or range of addresses to block. Here, the result is more substantive: Anyone trying to access your site from these addresses will get an error message instead of seeing your page.

Which IP range we should block to restrict access to your Web application from Internet?

To deny access to a block of IP addresses, simply leave off the last octet from the IP address: 123.456. 789. This blocks access to anyone using an IP in the range of 123.456.


2 Answers

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)

like image 120
Tyler Carter Avatar answered Sep 29 '22 23:09

Tyler Carter


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.

like image 38
Marcus Adams Avatar answered Sep 29 '22 22:09

Marcus Adams