WordPress Code Snippets

A fresh mix of code snippets and tutorials

PHP trap for bad bots

75

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 robots.txt file:

Step 2: .htaccess

In your site’s root .htaccess file, include the following code at the beginning of the file:

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:

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.

Learn more

.htaccess made easy