Advanced IP Ban PHP Script
Posted on September 12, 2008, Filled 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!
- September 12, 2008
- article by Gabriel C.
- 2 comments
Related Posts
PHP: How to select a random value from an array using a specified rangeat September 20, 2008
Advanced AJAX Star Rating Scriptat October 27, 2008 with 1 comment
PHP: Usage of Range() Function (Alphabetical & Numerical Output)at September 2, 2008
How to Create an Advanced PHP (bad, naughty) Words Filterat October 26, 2008 with 6 comments
PHP: How to redirect a visitorat May 21, 2008

2 Replies to "Advanced IP Ban PHP Script"
January 31, 2009 at 9:19 PM
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?
February 8, 2009 at 4:47 PM
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