Blocking Multiple IP Addresses With PHP

It is sometimes necessary to block people from using your site, dependent on their IP address. A users IP address can be detected by PHP using the $_SERVER superglobal and the parameter REMOTE_ADDR.

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', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
}
// 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!"

Comments

$deny = file('blocked_ips.txt' , FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

Thank you for the article, but I think I should add this code.

Permalink

Thanks Võ, that's a good suggestion. I've altered the example above to include that.

Name
Philip Norton
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
2 + 3 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.