Spammer Trap
Another bad-bot trap to keep spammers and other scumbags away from your website.
Update! I’ve developed a free WordPress plugin that automates the spammer trap and really takes it to the next level. Check it out: Blackhole for Bad Bots
To create a spammer trap for your site, follow these steps.
Step 1: robots.txt
In your site’s robots.txt
file, add these lines:
User-agent: *
Disallow: /signup.php
This instructs all browsers to ignore any file named signup.php
(next step).
Step 2: PHP
Create a file named signup.php
and add the following code:
<?php // Spammer Trap
$badbot = 0;
$filename = "signup-log.dat"; // specify path to log file
$fp = fopen($filename, 'r') or die ('Error opening file.');
while ($line = fgets($fp, 255)) {
$u = explode(' ', $line);
if (ereg($u[0], $REMOTE_ADDR)) { $badbot++; }
}
fclose($fp);
if ($badbot == 0) {
$date = date("Y-m-d (D) H:i:s", time());
$data = "Bad bot @ $REQUEST_URI - $date \n" . "From IP: $REMOTE_ADDR \n" . "User-agent is $HTTP_USER_AGENT \n";
mail('email@example.com', 'spam trap', $data, "From: site@example.com"); // customize with your infos
$fp = fopen($filename, 'a+');
fwrite($fp,"$REMOTE_ADDR - $data \"$REQUEST_METHOD $REQUEST_URI $SERVER_PROTOCOL\" $HTTP_REFERER $HTTP_USER_AGENT\n");
fclose($fp);
die('Sorry but you do not have access.');
} ?>
In this code you’ll need to edit the second line (with path to your log file, which we create next), and the mail()
function (with your to and from email address).
Step 3: Log file
Next create the log file that will record data for bad bots and spammers. Preferably in the same directory as signup.php
, create a file named “signup-log.dat” and change it’s permissions to the least-restrictive settings required to enable it to be readable and writable by the server. Contact your host if unsure.
Step 4: .htaccess
Last step: protect your log file against all external access. Add these directives to an .htaccess file located in the same directory as your signup log file:
<Files "*.dat">
Order allow,deny
Deny from all
</Files>
With everything in place, it’s time test that everything is working. To do so, visit the signup file that is no explicitly forbidden via robots.txt. Any bad bots or spammers or anyone that visits the “signup” file will be added to the log file.
Step 5: extending
Once everything is working as expected, you can automatically block bad bots by including this code in your web pages:
<?php $badbot = 0;
$filename = "signup-log.dat"; // specify path to log file
$fp = fopen($filename, 'r') or die ('Error opening file.');
while ($line = fgets($fp, 255)) {
$u = explode(' ', $line);
if (ereg($u[0], $REMOTE_ADDR)) { $badbot++; }
}
fclose($fp);
if ($badbot == 0) {
die('Sorry but you do not have access.');
} ?>
Of course, this is just a simple example to get you started. Feel free to customize as needed to create the perfect spammer trap.