Basic IP Banning
By: Daniel

So you want to create a basic IP banning system to ban users from your site. You know their IP address and don’t want them viewing the content on your page. This code will do the trick for you!

<?php
// List all ip addresses below
$denyIP = array('192.168.1.100', '192.168.2.*', '192.168.3.10?');

$_allowed = true;

// Loop through all IP addresses
foreach($denyIP as $dip){
	$dip = str_replace('.','\.',$dip);
	$dip = str_replace('*','[0-9]{1,3}',$dip);
	$dip = str_replace('?','[0-9]{1}',$dip);
	if(ereg("^{$dip}$", $_SERVER[REMOTE_ADDR])) $_allowed = false;
}
if(!$_allowed) {
echo 'You have been banned from this site. Sorry!';
die();
}
echo $_SERVER[REMOTE_ADDR].' Approved!';
?>

In the $denyIP array, supply all the IP addresses you wish to ban. Putting a ? in the IP address will allow for any IP address with the xx? to be blocked, where xx are known and ? is unknown. You can also put a * in the IP address and block the whole range of IP addresses.

To use this script, place it at the head of all the files you wish to ban users from. Very basic, but it does the job.

Download a demo of this script that uses a database and has an admin backend: IPBan.zip

1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 5.00 out of 5)
Loading ... Loading ...

6 Responses to “Basic IP Banning”

  1. r Says:

    this is good web site

  2. bazish Says:

    Excellent job, i like the way you explain your scripts and all are working accurately. which is proof of your high knowledge of PHP.
    thanks for sharing all these scripts.

  3. anony Says:

    This is a good script, though there is possibilities of SQL injection in places. Nice work though!

  4. Daniel Says:

    There is no SQL in this script so there are no possibilities of SQL injection.

  5. Michael Says:

    You could use…

    if (strpos($_SERVER['REMOTE_ADDR'], $dip) === 0) {
    $_allowed = false;
    }

    … and not need to use the ’str_replace’ functions. To allow for wildcards, just stop the banned address earlier, i.e. ‘192.168.2′.

  6. Rocky Says:

    $denyIP = array(‘192.168.1.100′, ‘192.168.2.*’, ‘192.168.3.10?’);

    $_allowed = true;

    // Loop through all IP addresses
    foreach($denyIP as $dip){
    $dip = str_replace(‘.’,'\.’,$dip);
    $dip = str_replace(‘*’,’[0-9]{1,3}’,$dip);
    $dip = str_replace(‘?’,’[0-9]{1}’,$dip);
    if(ereg(“^{$dip}$”, $_SERVER[REMOTE_ADDR])) $_allowed = false;
    }

    if(!$_allowed) {

    echo ‘You have been banned from this site. Sorry!’;
    exit;

    } else {
    // Allow Access To The Website
    }
    ?>

    if (strpos($_SERVER['REMOTE_ADDR'], $dip) === 0) {
    $_allowed = false;
    }
    // Run Check

Leave a Reply

geovisitors