Security: Automatically block someone using a PHP script

In this article we provide you with a script that will automatically block people using a PHP script and a htaccess file.

This can be helpful for a number of reasons. For example, you can use this script to ban people that are snooping around your website, or to ban robots that don’t respect your robots.txt file.

Here is the PHP section of the script. To use this, create a file in your public_html directory and add the following content…

<?php// Get the IP address of the visitor so we can work with it later.$ip=$_SERVER['REMOTE_ADDR'];// This is where we pull the file and location of the htaccess file. If it's in// the same directory as this php file, just leave it as is.$htaccess='.htaccess';// This pulls the current contents of your htaccess file so we can search it later.$contents=file_get_contents($htaccess,TRUE)
OR exit('Unable to open .htaccess');// Lets search the htaccess file to see if there is already a ban in place.$exists=!stripos($contents,'deny from '.$ip."\n")
OR exit('Already banned, nothing to do here.');// Here we just pull some details we can use later.$date=date('Y-m-d H:i:s');$uri=htmlspecialchars($_SERVER['REQUEST_URI'],ENT_QUOTES);$agent=htmlspecialchars($_SERVER['HTTP_USER_AGENT'],ENT_QUOTES);$agent=str_replace(array("\n","\r"),'',$agent);// If you would like to be emailed everytime a ban happens, put your email// INSIDE the quotes below. (e.g. 'my@email.com')$email='';// This is where we can whitelist IP's so they can never be banned. Simply remove // the // from the front of one of the example IP addresses below and add the // address you wish to whitelist. Make sure that you leave the single quotes (') // intact and the comma at the end. Adding a person to the whitelist AFTER they // have been banned will NOT remove them. You must open the htaccess file and // locate their ban by hand and remove it.$whitelist=array(// '123.123.123.123',// '123.123.123.123',// '123.123.123.123',);// This section prevents people from being sent to this script by mistake// via a link, image, or other referer source. If you don't want to check// the referer, you can remove the following line. Make sure you also// remove the ending } at the very end of this script.if(empty($_SERVER['HTTP_REFERER'])){// This section will write the IP address to the htaccess file and in turn// ban the address. It will however check the whitelist above to see if// should be banned.if(in_array($ip,$whitelist)){// User is in whitelist, print a message and end script.echo"Hello user! Because your IP address ({$ip}) is in our whitelist,
you were not banned for attempting to visit this page. End of line.";}else{// User is NOT in whitelist - we need to ban em...$ban="\n# The IP below was banned on $date for trying to access {$uri}\n";$ban.="# Agent: {$agent}\n";$ban.="Deny from {$ip}\n";file_put_contents($htaccess,$ban, FILE_APPEND)
OR exit('Cannot append rule to .htaccess');// Send email if address is specifiedif(!empty($email)){$message="IP Address: {$ip}\n";$message.="Date/Time: {$date}\n";$message.="User Agent: {$agent}\n";$message.="URL: {$uri}";mail($email,'Website Auto Ban: '.$ip,$message);}// Send 403 header to browser and print HTML pageheader('HTTP/1.1 403 Forbidden',TRUE);echo'<html><head><title>Error 403 - Banned</title></head><body>
<center><h1>Error 403 - Forbidden</h1>Hello user, you have been
banned from accessing our site. If you feel this ban was a mistake,
please contact the website administrator to have it removed.<br />
<em>IP Address: '.$ip.'</em></center></body></html>';}}

The next section is the basic htaccess file that you will need. Create the .htaccess file in your public_html directory (or edit the one you already have) and add the following at the top…

<FilesMatch 403.shtml>
Order Allow,Deny
Allow From All
</FilesMatch>

Now add the following to the very bottom of your htaccess file.

############### START BANS ###############

Now, anyone that attempts to access block.php (for whatever reason) will automatically be blocked (unless you add them to the whitelist array).

Still have a question? Or need help?See an error in this article or want to suggest a missing topic? Please leave us a comment below! If you need technical support with your account, please email us, chat live with a representative, or call us!

30 Comments

J Holland September 20, 2013 at 4:11 pm

Also, is this the /block.php file mentioned in the .htaccess file? I see no mention here of what to call this file. I’m pretty much a n00b and need everything explained to me. ;)

John Oliver at Site5 September 24, 2013 at 1:42 pm

Hello J,

I hope this reply finds you well!

If you are referring to the htaccess file located in our “How to Automatically Block someone who is Snooping around your Site” article, yes this is the php file intended to work with that htaccess file.

The file itself can be called “block.php” when you add it to your website.

If you could reply with more information about what you are attempting to do, I will be happy to walk you through the entire process or recommend another solution that may be better suited for your website.

I look forward to hearing from you and helping you. :)

peter September 30, 2013 at 11:12 am

Hello John ,

Could you please explain me what should i put into the php file and what should i put into the htaccess.

where can i put the IP adress that i don’t want to let to visit my website ?

if you can send me an email with 2 attachements ( HTTACCESS AND THE PHP ) ..my email is: uk-trucks@hotmail.com or post it here . thanks

John Oliver at Site5 October 8, 2013 at 1:50 pm

Hello Peter,

The script in this article is mostly intended to block people who snoop around your site or to block bots that don’t respect your rebots.txt file.

If you are just looking to block IP addresses, I would recommend that you use the IP Ban Manager found in both cPanel and SiteAdmin.

For information on how to access this feature, please see one of the following two links…

There is no need to call this php file in any other, and no need to add a directive to it in .htaccess, other than the ones mentioned in the article. This file simply sits on your website, and any automated ‘snooper’ scripts will hit it, triggering the block. As the file is not part of your site, and has no links to it, there are very few non-malicious reasons for an IP address to hit the file.

1 – Yes, it does provide an extra layer of protection, which is always a good thing :)

2 – In a robots.txt file, you can specify which bots to block, which bots to allow, or even block all bots. It is highly configurable, and offers many options. If you would like, we can certainly help you get this set up properly, but we would need to do so through a helpdesk ticket, which you can enter via BackStage.

Can you open a ticket on this with our support team, via BackStage, so we can take a look?

Russ March 4, 2014 at 11:08 am

This script works like tripwire. Great stuff here!
I have the script route to a decoy page rather than a 403 forbidden page.

If people don’t know they’re being blocked then it removes the threat.

Marco April 28, 2014 at 6:21 pm

Was not able to get this alternative to work: http://perishablepress.com/blackhole-bad-bots/ Maybe it helps others. Have the above script on the server and actually linked it from all pages on the website. The link (hidden) with a Display: None and Nofollow url. Also added a disallow in the robots.txt to the file. Will check the .htaccess now and then and clear out the banned ip’s.

david62311 September 26, 2014 at 2:58 am

This is a great script. Thank you very much for sharing it. What J Holland was saying up there that when it was explained, it never said to name it block.php. This code works on any page I would recommend to put the code on any page that seems to be getting a lot of bot hits. I added mine to a fake register.php and it worked nicely when I ran my tests. It sent me an email right away when I attempted to access the page without being on the whitelist. I tested it out when I was on the whitelist too and that work nicely.

Most themes come with the option to edit them. You can normally do this in the admin area of WordPress, but if you cannot you can manually edit the files using your File Manager in SiteAdmin. The files to edit would be located in public_html/wp-content/themes/THEMENAME

Hi Mark! This script is essentially watching for IP addresses that might be scraping your site and checking every file. So, when “block.php” is accessed, the IP address accessing the file is added to the ban list and is blocked from accessing your site in the future. Other than that, there is no true detection method to finding out if an IP address is malicious or not. It is merely found to be suspicious due to accessing a file that’s not related to your site in any way.