Ban or allow IP Addresses (not using htaccess)

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.txt (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.

This first script can be used to ban an IP Address from any function on your site.
You can download this script as a .txt file.  Remember to rename the file as a .php file.

– – Start Script Here – –
<?php
$ipArray = file('ip.txt');
foreach ($ipArray as $ipTest) {
if (substr_count($_SERVER['REMOTE_ADDR'],trim($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
$ipArray = file('ip.txt');
unset($allowed);
foreach ($ipArray as $ipTest) if (substr_count($_SERVER['REMOTE_ADDR'],trim($ipTest)) != "0") $allowed = true;
if ($allowed != true) {
header('location: /banned.htm');  // the banned display page
die();
}
?>

– – End Script Here – –