Site5 - Built For Designers & Developers MENU
Home  ›  Security  ›  Security: Automatically block someone using a PHP script

Security: Automatically block someone using a PHP script

30 Comments

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).

Still have a question? Or need help?
If you need technical support with your account, please email us or chat live with a representative.

30 Comments

  • 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. ;)

    • 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. :)

      • 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

        • 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!

    • could you teach me how can i use this php .

      i have copied everything and pasted into my php file . it is not working

  • 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

    • 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.

  • 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

    • 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.

  • not working !

    • 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?

  • 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

    • 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.

      • I tryed the

        header(‘Location: index2.html’);

        Still comes down to the 403

        • Hi Hans,

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

  • 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.

  • 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.

  • 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.

  • thanks guys sharing security blok ip adreess great work.

  • 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/

    • 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

  • Thank you James

  • Thank you James

  • How do i delete the blocked ip after 5 minutes automatically?

    • 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.

      • There is something ready ?

        • 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.

  • Thank you James

  • 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.

    • 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.

Money Back Guarantees