I use a simple comment validation hack on my site as a first defense against spam. The system uses what’s known as a Turing number, named after the mathematician Alan Turing. If you have ever signed up for an e-mail account at yahoo or gone to e-gold’s website, you know what I’m talking about. Here’s how I did it.

This hack involves editing two wordpress files and tossing some php scripts in your script directory. It requires you have the gd libraries available to php. On *nix computers you can type php -i to check out your php configuration.

Add the following to the top of wp-comments-post.php. I added it right after the line require( dirname(__FILE__) . ‘/wp-config.php’;. wp-comments.php should be in your wp root directory, and is the file that processes comment POST’s.


// verification system //
require( '/var/www/scripts/iv_encode.php' );
$id = $_POST['id'];
$key = $_POST['key'];
$verify = $_POST['verify'];
$decid = urldecode(md5_decrypt($id, $key));
if (('' == $verify) || ( $decid != $verify )) {
die( __("Error: if you are not a spammer, please fill in the turning number. this number must match with the image above it.") );
}
// end verification system //

Next we need to edit the file(s) that output the comment form itself on your pages. The files to look at include comments.php and comments-popup.php. You may use one or both, and it’s possible they may have different names. Check your themes directory if your using wp 1.5 or greater. Once you’ve found the right file, add the following somewhere near the top.


<?php
// comment verification system //
require_once ('/var/www/scripts/iv_encode.php');
$string = md5(rand(0, microtime()*1000000));
$verstr = substr($string, 3, 7);
$key = md5(rand(0,999));
$encid = urlencode(md5_encrypt($verstr, $key));
$encid2 = md5_encrypt($verstr, $key);
?>

Finally, we need to add the actual text field and Turing image itself to the comment form. The following code snippet should do the job.


<?php
echo "<img alt=\"turing number\" src='/scripts/iv_num2img.php?id=$encid&key=$key' /><br />";
?>
<input type="text" name="verify" id="verify" value="" size="18" />
<label for="verify" style="color: #660099; background-color: #F0F0F0;">turing number</label>
<input type="hidden" name="key" value="<?php echo $key; ?>" />
<input type="hidden" name="id" value="<?php echo $encid2; ?>" />

Lastly, toss the php scripts below into your script directory. I believe I lifted these scripts from the php wiki and hacked them a bit, so if you are the original author, thanks. I’ve combined them into one file to make them easy to download. The snippets above assumed you are putting these scripts in /var/www/scripts, so you may need to edit them to reflect their actual location.

verify scripts