Block Multiple IP Addresses with PHP
Let’s face it. There’s just as much scum on the Internet as there is out there in the “real world.” Maybe even more, who knows. From scammers and spammers to scrapers and crackers, the Web is just crawling with all sorts of pathetic scumbags. As predictably random as much of the malicious activity happens to be, it is virtually guaranteed that you will be hounded by at least a few persistent IP addresses that, for whatever reason, have latched on and just won’t let go. Like evil parasites, they plague you night and day, haunting you and making your online life a living hell. Perhaps they leave endless spam comments; perhaps they are just mindless trolls giving you grief; or perhaps they continue to take flying stabs at the security of your website. Whatever the behavior, once you have determined that you need to block a collection of bad IPs, you have many ways to get the job done. Here is a simple way to blacklist multiple IP addresses with a little PHP magic..
Throw Down
Edit the following code with your blacklisted IPs and drop into the page or header file of your choice to enjoy immediate relief from relentless scumbags:
<?php $blacklist = array("123.456.789", "456.789.123", "789.123.456");
if(in_array($_SERVER['REMOTE_ADDR'], $blacklist)) {
header("Location: http://domain.tld/path/custom.php");
exit();
} ?>
Recap: edit the IPs in the first line to suit your needs. You will also want to edit the header path in the third line to reflect the location of your “special message” for the blocked IPs. This may be anything you wish: warm greetings, pictures of your bum, or even a virus unleashing the black death upon them. Whatever you do, have fun and be safe! ;) Alternately, if you don’t feel like taking the time to craft a loving page for your blocked frenz, replace the header URL in the third line with the viciously disturbing site of your choice. There are many great sites out there to choose from — so be creative!
Lastly, after you have carefully edited the PHP blacklist script according to your needs, place it into the top of your header.php
file or web pages of your choice. Any page featuring this code will be inaccessible to the IP addresses blacklisted in the first line. So grab, gulp, and go! This code will keep those nasty chimps far away from your precious pages! ;)
26 responses to “Block Multiple IP Addresses with PHP”
How’s this different than blocking these IPs from the .htaccess level? Any performance gain/hit I should know about?
In my opinion it’s better to block/redirect at the server-level to avoid invoking additional PHP resources. There are some situations where blocking via PHP is useful, however, such as when more advanced processing is required (eg, logging, custom headers, etc.).