Block Multiple IP Addresses from Text File with PHP
Here is a fun little tutorial. It shows how to block multiple IP addresses that are listed in a plain text file. It’s a nice little system to block bad IP addresses without using any database. For example, this is useful if you’ve got a bunch of IP addresses that you want to block quickly. Or if you just want to learn an easy way to block multiple IP addresses via PHP, this guide is for you..
Step 1: Create a list of IP addresses
First, create a text file and name it ip-address-list.txt
. Then add some IP addresses, like these for example:
123.123.123
111.111.111
222.222.222
113.113.113
223.223.223
331.331.331
000.000.000
Save the file and upload it to the same directory that will contain the following PHP script.
Step 2: Add the magic PHP script
In the same directory that contains ip-address-list.txt
, create a PHP file and add the following code:
// https://wp-mix.com/block-multiple-ip-addresses-text-file-php/
function wpmix_block_multiple_ip_addresses() {
$list = 'ip-address-list.txt';
$ip_addresses = array();
$fopen = fopen($list, 'r');
$string = fread($fopen, filesize($list));
fclose($fopen);
$array = explode("\n", $string);
for ($i = 0; $i < count($array); $i++) {
$ip_addresses[] = $array[$i];
}
foreach ($ip_addresses as $ip) {
$current_ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
if ($current_ip && filter_var($current_ip, FILTER_VALIDATE_IP) && str_starts_with($current_ip, $ip)) {
header('Location: https://example.com/?goodbye');
exit();
}
}
}
// call the function
wpmix_block_multiple_ip_addresses();
That’s all there is to it. Now upload both files to the server. Open your browser and request the PHP file. If it returns blank white screen, that means your IP address is not on the list (or there is an error). If you want to test that the script is blocking correctly, simply add your IP address to the text list and reload the page. Upon doing so, you should be redirected to https://example.com/?goodbye
.
There are myriad ways to customize the above script. For example, you can change the name and location of the text file. You can change the URL to which header()
is redirecting. Instead of redirecting to some URL, you can simply return a 403 “Forbidden” response:
header('HTTP/1.1 403 Forbidden');
Or you can straight-up block them with a simple die();
Note: The IP-blocking script above uses str_starts_with(), which requires PHP version 8 or better.
Note: The IP-blocking script matches IP addresses in wild-card fashion. So if the list contains an IP address 123.123
, and the visitor’s IP address is 123.123.123
or 123.123.000
, it will be blocked/redirected.