Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect an entire range/block of IP addresses with PHP?

Tags:

redirect

php

ip

I'm using the following snippet to redirect an array of IP addresses. I was wondering how I would go about adding an entire range/block of IP addresses to my dissallowed array...

<?php // Let's redirect certain IP addresses to a "Page Not Found"
$disallowed = array("76.105.99.106");
$ip = $_SERVER['REMOTE_ADDR']; 

if(in_array($ip, $disallowed)) {
 header("Location: http://google.com");
 exit;
}
?>

I tried using "76.105.99.*", "76.105.99", "76.105.99.0-76.105.99.255" without any luck.

I need to use PHP rather than mod_rewrite and .htaccess for other reasons.

like image 822
aegenes Avatar asked Sep 23 '09 15:09

aegenes


4 Answers

Here's an example of how you could check a particular network/mask combination:

$network=ip2long("76.105.99.0");
$mask=ip2long("255.255.255.0");
$remote=ip2long($_SERVER['REMOTE_ADDR']);

if (($remote & $mask)==$network)
{
    header("Location: http://example.com");
    exit;
}

This is better than using a string based match as you can test other masks that align within an octet, e.g. a /20 block of IPs

like image 193
Paul Dixon Avatar answered Nov 15 '22 02:11

Paul Dixon


Try the substr function:

$ip = '76.105.99.';
if (substr($_SERVER['REMOTE_ADDR'], 0, strlen($ip)) === $ip) {
    // deny access
}
like image 28
Gumbo Avatar answered Nov 15 '22 03:11

Gumbo


You can approach the problem in a different way.

If you want to ban 76.105.99.* you could do:

if (strpos($_SERVER['REMOTE_ADDR'], "76.105.99.")!==FALSE)
{
    header ('Location: http://google.com');
} 
like image 36
rogeriopvl Avatar answered Nov 15 '22 03:11

rogeriopvl


Who exactly are you interested in blocking? You can use PHP or apache to block (or allow) a bunch of specific IP addresses.

If you are interested in blocking people from an entire country for example, then there are tools that give you the IP addresses you need to block. Unfortunately, it's not as simple as just specifying a range.

Check out http://www.blockacountry.com/ which generates a bunch of ip addresses you can stick in your .htaccess to block whole countries.

like image 1
Evernoob Avatar answered Nov 15 '22 04:11

Evernoob