Adding additional comment spam protection to sNews, the math/image hybrid captcha
Updated February 25th, 2009, please read this entry for the updated tutorial. Version 2 is vastly improved, it is recommended you upgrade if using version 1.
After waking up this morning to find most all of my articles had a shiny new spam comment, I decided to try out a new method to reduce such annoyances.
This mod will take your math captcha question output and post it as an image, so it remains human readable, but a bot doesn't see the "5 + 6 =" so if they want to hack it, not only does the bot have to decipher the text it will still then have to do the math.
Not a cure-all I'm sure and it won't stop human powered spam (and the key can be decoded and figured out but it's an added annoyance and overhead to bot programmers), but hopefully it'll quell some of the auto spammers that have figured out the basic math captcha.
So let's begin by saving the following code as capgen.php
<?php
$mathkey = "56454669"; // change this to any string of numbers you like
$key = strip_tags($_GET['key']);
$decode = base64_decode($key);
$keys = explode($mathkey, $decode);
$x = $keys[0];
$y = $keys[1];
$my_img = imagecreate(80, 20);
imagesavealpha($my_img, true);
$trans_color = imagecolorallocatealpha($my_img, 0, 0, 0, 127);
imagefill($my_img, 0, 0, $trans_color);
$text_color = imagecolorallocate($my_img, 0, 0, 0);
imagestring( $my_img, 5, 10, 3, "$x + $y =",
$text_color);
imagesetthickness ($my_img, 5);
header("Content-type: image/png");
imagepng($my_img);
imagedestroy($my_img);
?>
Make sure to change the math key, now upload that to your public_html folder. OK, back up your snews.php file and then find the function mathCaptcha, and replace it with the following;
// MATH CAPTCHA
function mathCaptcha() {
$mathkey = "56454669";// make sure keys match!
$x = rand(1, 9);
$y = rand(1, 9);
$_SESSION[_SITE.'mathCaptcha-digit'] = $x + $y;
$math = '
<p><label for="calc">
* '.l('math_captcha').':
</label><br />';
//$math .= $x.' + '.$y.' = ';
$key = base64_encode($x.$mathkey.$y);
$math .= '<img src="'._SITE.'capgen.php?key='.urlencode($key).'" alt="" />';
$math .= '
<input type="text" name="calc" id="calc" />
</p>';
return $math;
}
That's it! Now upload your edited snews.php file and you should have basic image generation instead of plain text for the math captcha function. As always, let me know if I left anything out or if you encounter any problems or issues. Yes, I'm using it on my site, just look below, though I'm using a slightly different scheme with multiple keys sprinkled so it can't be pattern matched.
Comments
RSS Comments Feed
Matt
mickey
Poppoll
PP