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. '[email protected]') $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 specified if (!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 page header('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).
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: [email protected] 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…
http://kb.site5.com/control/siteadmin/siteadmin-ip-ban-manager/
http://kb.site5.com/control/cpanel/cpanel-ip-deny-manager/
If you have any questions, please feel free to leave a comment here, or if you prefer, you can contact our support team directly by opening a ticket through Backstage.
Happy Hosting!
peter September 30, 2013 at 10:56 am
could you teach me how can i use this php .
i have copied everything and pasted into my php file . it is not working
galvin November 9, 2013 at 1:14 pm
Please explain how this call .php file. Do I need to .htacces file to add the name of the .php file.
IP address .htacces when added to deny from xxx.xxx.xxx.xxx on the site will receive message
Internal Server Error
What does this script and how to connect with htacces
James Davey November 12, 2013 at 9:09 am
Hi Galvin,
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.
Christian Desjardins November 10, 2013 at 11:44 am
HI,
I find thie information very helpful, and I will try to use this but I have 2 questions :
1) If I have purchased the malware protection from site5 for my web site, is it useful to also use this methos of protection?
2) Do I need any special code or information in my robot.txt file in order to not block robots that I want to refer my web site (google, etc.)
Thanks for your answer
Christian
James Davey November 12, 2013 at 9:06 am
Hello Christian,
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.
Hemin Michael January 19, 2014 at 3:53 pm
not working !
James Davey January 20, 2014 at 8:57 am
Hello Hemin,
I am sorry to hear that. To look into why this is happening, can you open a ticket with our support team, via BackStage?
Hans de Bruin February 10, 2014 at 6:28 am
Is there a little script add, so the banned IP gets redirected to a different (page.html)
And not the 403.shtml ?
Thanks in advanced
James Davey February 10, 2014 at 9:03 am
Hello Hans,
A second script would not be required. You would just need to edit this section:
// Send 403 header to browser and print HTML page
header(‘HTTP/1.1 403 Forbidden’, TRUE);
Rather than sending the 403 header, a 301 redirect to the page of your choice could work here.
Hans de Bruin February 10, 2014 at 9:27 am
I tryed the
header(‘Location: index2.html’);
Still comes down to the 403
James Davey February 10, 2014 at 10:34 am
Hi Hans,
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.
JASA SEO December 8, 2014 at 8:11 pm
thanks guys sharing security blok ip adreess great work.
Leo January 30, 2015 at 3:52 am
There is html code that one would insert at top of your index page. Where would this go in WordPress site with it being replaced by theme updates?
Here is the code: http://kb.site5.com/security/how-to-block-bots-that-dont-respect-your-robots-txt-file/
James Davey January 30, 2015 at 6:19 am
Hi Leo,
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
Leo January 30, 2015 at 2:34 pm
Thank you James
خرید هاست February 5, 2015 at 2:47 am
Thank you James
bill March 23, 2015 at 5:01 pm
How do i delete the blocked ip after 5 minutes automatically?
James Davey March 24, 2015 at 5:53 am
Hi Bill,
That would require another script to delete lines from your .htaccess file periodically. You would need to set this on a cronjob, and the shortest interval would be 15 minutes, not five.
bill March 24, 2015 at 7:54 am
There is something ready ?
James Davey March 24, 2015 at 11:28 am
No, we have nothing specific for this at the moment. This would be pretty simple to put together, though, if you are comfortable with bash scripting.
جامعة غرداية June 23, 2015 at 5:11 am
Thank you James
Mark June 9, 2016 at 11:56 am
Hi,
I stumbled across this post searching for ways to ban malicious visitors. How does the file detect that an IP is potentially malicious, since it’s not linked to any page on the site?
Thanks.
Corey Mahon June 23, 2016 at 8:49 am
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.