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(
} 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!';

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 ( was blocked!"


$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.


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

Philip Norton

Add new comment

The content of this field is kept private and will not be shown publicly.
7 + 8 =
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.