Dvorak's comment spam fix

As a regular listener to This Week In Tech I heard on the latest show John C Dvorak's anti-spam provider Marc Perkel at ctyme.com has come up with a way to prevent comment spam on any site running apache.

I went over to John's site to get the low down and basically the method uses mod_rewrite to deny anyone trying to access the form if the referrer doesn't come from the domain of that site. This is a similar trick to one used to show alternative images to anyone visiting the site of someone that has linked directly to images on your site.

<location /blog/wp-comments-newpost.php>    
  RewriteEngine On
  RewriteCond %{HTTP_REFERER} !^.*dvorak.org/.*
  RewriteRule ^.* http://www.ctyme.com/comment-spam.html
</location >

The big flaw with this method is that the HTTP referrer can easily be spoofed on the user-agent therefore rendering this method useless once spammers catch on. A better way is to use a token method. Assuming you are using PHP, to implement this is quite simple. Create a token and then put the token in a hidden field on your form. At the same time you need to put the same token into the $_SESSION array.

  $secret = 'magicalspambustingnumpties';
  $token = md5(rand(1, 1000).$secret);
  $_SESSION['token'] = $token;

<input type="hidden" name="token" value="<?=$token? >" />

On the page that receives the posted form, just check that the posted token field matches the token in the session. Unlike the HTTP referrer method this user-agent cannot interfer with this method. To take this event further you could even add a timeout mechanism to this but on it's own this should suffice.