Block Multiple IP Addresses Using PHP

Jun 03, 2014, by admin

Sometimes we need to ban particular visitors to access our website. For this, the most common reason is spammers and scrapers that perform malicious activity from few persistent IP addresses. Although there are so many tricks to block multiple IP addresses such as using htaccess, Apache mod_rewrite but here you’ll know the simple trick to block multiple IP addresses using PHP.

homeimg03

The code includes two ways to load the list of IP addresses. The first is by hard coding it into an array, and the second is by the use of a plain text file called “blocked_ips.txt”. The format of this file is simply a list of IP addresses, with one address on each line. Through the use of the file() function this file is loaded as an array into of addresses.

if ( !file_exists(‘blocked_ips.txt’) ) {
 $deny_ips = array(
  ‘127.0.0.1’,
  ‘192.168.1.1’,
  ‘83.76.27.9’,
  ‘192.168.1.163’
 );
} else {
 $deny_ips = file(‘blocked_ips.txt’);
}
// read user ip adress:
$ip = isset($_SERVER[‘REMOTE_ADDR’]) ? trim($_SERVER[‘REMOTE_ADDR’]) : ”;
 
// search current IP in $deny_ips array
if ( (array_search($ip, $deny_ips))!== FALSE ) {
 // address is blocked:
 echo ‘Your IP adress (‘.$ip.’) was blocked!’;
 exit;
}

There are two things you should be aware of when using this method.

The first is that a users IP address can change due to many factors. They could either move to a different building or their ISP could assign a different IP address for them.

The second thing to be aware of is that you should be careful when entering IP addresses so that you don’t block search engine spiders from looking at your site. Instead of spidering your content they will just index the phrase “Your IP address (0.0.0.0) was blocked!”