Coding with Jesse

Avoiding Comment Spam with JavaScript

Originally I explained this on the Code Igniter forum, and since others are blogging it, I thought I should bring it here.

I guess I was nervous about sharing my anti-spam techniques on my own blog in case any spam bots are smart enough to read this article and somehow mutate and adapt. We'll see.

For a while, I had no problems with comment spam. Then I started to get a couple. Then one day I got like 50 at once, so I did something "extreme" - I made it so users have to have JavaScript to submit comments. I have a randomly generated spam key in PHP, and then use something like this on the page:

<form id="cform" style="display:none">
    <input id="txtauthor" name="<?= $spam ?>a"/>
    <input id="txtemail" name="<?= $spam ?>e"/>
    <input id="txturl" name="<?= $spam ?>u"/>
    <textarea id="txtbody" name="<?= $spam ?>b" rows="10" cols="40"></textarea>
    <input type="hidden" id="antispam" name="antispam"/>
</form>
<script type="text/javascript">
    document.getElementById('cform').style.display = 'block';
    document.getElementById('antispam').value = '<?= $spam ?>';
</script>
<noscript>Sorry, you need JavaScript to post comments.</noscript>

So if the spam key is 'xxxx' the author field is 'xxxxa', email 'xxxxe', etc. The spam key is filled using JavaScript. Then on the server side I do this:

if (isset($_POST['antispam'])) {
    $antispam = $_POST['antispam'];
    $cauthor = $_POST[$antispam . 'a'];
    $cbody = $_POST[$antispam . 'b'];
    $cemail = $_POST[$antispam . 'e'];
    $curl = $_POST[$antispam . 'u'];
    if ($cbody && $cauthor)
        addComment($id, $cemail, $cauthor, $cbody, $curl);
}

This has majorly cut down on the number of comment spam I get. I still get the occasional one here and there, but they must all be done by hand instead of with some automated bot.

Unfortunately, this method means that users without JavaScript can't post comments on here. I regret that, but since nobody posts comments on here anyways, I figure it's not such a loss. :) One day, I would like to add some kind of captcha or approval system to allow posting of comments without JavaScript.

Published on August 16th, 2006. © Jesse Skinner

About the author

Jesse Skinner

Hi, I'm Jesse Skinner. I'm a web development coach & consultant. I teach web development teams how to scale up their server infrastructure, improve automated testing and monitoring, reduce costs, and modernize their legacy systems. I focus on empowering teams through customized training and coaching.

Feel free to email me. I'm eager to hear about your challenges and see how I can make your life easier.