Advanced IP Ban PHP Script

Posted on September 12, 2008, under PHP,  Bookmark it

Hi,

This script is useful if you want to restrict the access to some people on your site, based on their IPs. There are 2 lists which can be used: one which has a list of the IPs you want to ban and one which you can use to ban a range of IPs. The script checks both lists and if the Visitor’s IP is in the list then the script will show a message to the user and exit.

<?php
/* List with IPs */
$ban_ip_list = array('68.180.206.184', '64.233.167.99', '207.46.232.182');

/* List with IP ranges. Use the '*' as the range selector */
$ban_ip_range = array('69.*.83.197');

/* Visitor's IP Address */
$user_ip = $_SERVER['REMOTE_ADDR'];

/* Message to output if the IP is in the ban list */
$msg = 'You do not have permission to access this page.';

/* Message to output if the IP is in the ban list */

    if(in_array($user_ip, $ban_ip_list))
	{
	  exit($msg);
	}

/* Check if the Visitor's IP is in our range's list */

if(!empty($ban_ip_range))
{
foreach($ban_ip_range as $range)
{
	$range = str_replace('*','(.*)', $range);

    if(preg_match('/'.$range.'/', $user_ip))
	{
	  exit($msg);
	}
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE>Welcome to My site</TITLE>
 </HEAD>
 <BODY>

  Here is my site content.
 </BODY>
</HTML>

Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!

Get our RSS Feed!

2 Replies to "Advanced IP Ban PHP Script"

  1. I know this is kind of an old topic, but I was wondering, what if you wanted to allow those certain IPs? I was trying to rewrite some of the code to do this, but something keeps on messing up with the IP range. Any suggestions?

  2. it can be done but it would be pointless as its a ban IP script but if you wanted to add a allowed list you would have to do if and else statements instead of foreach()

    <?

    $allowipfile = "allow.php";
    $banipfile = "ban.php";
    $ip = $_SERVER['REMOTE_ADDR'];

    $allow = file($allowipfile);
    $deny = file($banipfile);

    if (in_array ($ip, $allow)) {
    header("location: index2.php");
    }
    elseif(in_array($ip, $deny)) {
    header("location: banned.php");
    exit();
    }
    ?>

    im new to php and still trying to understand the in's and out's to the code but i think the above will work or if anyone can adapt or correct any mistakes i may have made writing the above code please do so

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)