Another effective trap for bad bots and spammers, built with PHP and a slice of .htaccess.
Step 1: robots.txt
First, instruct all bots to ignore our trap script (to be named “testing.php”). Add these lines to your site’s
User-agent: * Disallow: /testing.php
Step 2: .htaccess
In your site’s root .htaccess file, include the following code at the beginning of the file:
# trap for bad bots SetEnvIf Request_URI "^(/403.*\.html|/robots\.txt)$" welcome <Files *> Order deny,allow Deny from env = goodbye Allow from env = welcome </Files>
Note: the next step adds a script that needs write-access to this .htaccess file. It’s critical that you do not use a more permissive setting than 606, which should work fine. DO NOT use this bot trap technique if anything greater than 606 permissions (or equivalent) are required for the .htaccess file.
Step 3: PHP
Next, create a blank PHP file named “testing.php” and add the following code:
<?php // trap for bad bots $htaccess = "/var/www/public_html/.htaccess"; // specify correct path to root .htaccess file $content = "SetEnvIf Remote_Addr ^".str_replace(".","\.",$_SERVER["REMOTE_ADDR"])."$ goodbye\r\n"; $content .= fread($handle, filesize($htaccess)); $handle = fopen($htaccess, 'r'); fclose($handle); $handle = fopen($htaccess, 'w+'); fwrite($handle, $content, strlen($content)); fclose($handle); mail( // customize mail with your infos "email@example.com", "Another bad bot bites the dust..", "Banned IP: " . $_SERVER["REMOTE_ADDR"] . "\r\n" . "User Agent: " . $_SERVER["HTTP_USER_AGENT"] . "\r\n" . "Referrer: " . $_SERVER["HTTP_REFERER"], "From: firstname.lastname@example.org" ); die("Sorry no access."); ?>
This file must be “readable” by visitors, so make sure its permissions are CHMOD 604 or equivalent.
Things to edit: the path to your .htaccess file, and the “to” and “from” email fields in the
mail() function. Once everything is in place, visit the
testing.php in your browser to see how it all works. Customize as needed to suit your needs.
Like our new Facebook Page to show support!