How to Ban or allow IP Addresses (not using htaccess) using

Post Reply
Tony
Lieutenant
Lieutenant
Posts: 86
Joined: Tue Jul 21, 2009 4:11 pm

How to Ban or allow IP Addresses (not using htaccess) using

Post by Tony » Sun Nov 29, 2009 4:50 am

While a .htaccess file can be used to ban or allow, it cannot be selective by function. This is something you can easily do with a script.

In these examples the IP Addresses are in a file called IP.dat (in the same directory as the script) with one address per line. These scripts can also ban or allow based on partial IP Addresses. The code in these scripts must be placed before any other output to the browser (for this page) as they use the header() function for the redirection.

Code: Select all

<?php
$ip = $_SERVER['REMOTE_ADDR'];
$ipArray = preg_replace("#\r\n?|\n#","",file('IP.dat'));  // read the file into an array and remove new line breaks (should cover all OS)
foreach ($ipArray as $ipTest) {
  if (substr_count($ip, $ipTest) != "0") { 
    header('location: /banned.htm');  // the banned display page
    die();
  }
}
?> 
- - End Script Here - - 

For the opposite function, the below script can be used to only allow the specified IP Addresses. 
You can download this script as a .txt file.  Remember to rename the file as a .php file.

- - Start Script Here - -
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$ipArray = preg_replace("#\r\n?|\n#","",file('IP.dat'));  // read the file into an array and remove new line breaks (should cover all OS)
unset($allowed);
foreach ($ipArray as $ipTest) if (substr_count($ip, $ipTest) != "0") $allowed = "yes";
if ($allowed != "yes") {
    header('location: /banned.htm');  // the banned display page
    die();
}
?>
Post Reply

Return to “PHP & MySQL”