Blocking Multiple IP Addresses With PHP

Tuesday, May 20, 2008 - 09:32

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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!"

Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Add new comment