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

I'm Jesse Skinner. I'm a self-employed web developer. I love writing code, and writing about writing code. Sometimes I make videos too. Feel free to email me if you have any questions or comments, or just want to share your story or something you're excited about.