Add Math Captcha Spam Protection to your Contact Form

I recently had to add captcha to one of my web contact forms as I was receiving a lot of spam from it. I went for a simple math captcha as I think it is easier to understand than Googles reCaptcha. Since the implementation turned out to be much easier than expected, I thought I’d share it with the world.

First, I added the the math script to my PHP form:

//Math Script

if(!isset($_POST['submitted'])) {
   session_start();
   $digit1 = mt_rand(1,6);
   $digit2 = mt_rand(1,6);
   $math = "$digit1 + $digit2";
   $_SESSION['answer'] = $digit1 + $digit2;
}

What this function does is simply adding two random numbers between 1 and 6 to each other and holds te result in the $math variable. You can simply increase or decrease the values of $digit1 and $digit2 if you feel the need to (Source: Stackoverflow).

Next, I had to find the post submit check of my contact form and hook into it. This is usually a lift of if statments checking if the fields have been filled out. Look for email and message variables. In my case this looked like this:

if(isset($_POST['submitted'])) {
  if(trim($_POST['contactName']) === '') {
   $nameError = 'Please enter your name.';
   $hasError = true;
   } else {
   $name = trim($_POST['contactName']);
   ...

I simply added another test for the Math captcha at the end of the tests:

if ($_SESSION['answer'] != $_POST['answer'] ) {
    $commentError = 'Please answer the math question.';
    $hasError = true;
  }

If the Math question has been answered wrong it will set the variable $hasError to true and thus not allow the form to be sent. The $hasError is a defined variable of the original form check and is probably different in your case.

The last thing I did was adding the input field to the form so the user can answer the math question. Usually forms are built using unordered lists (look for <li> tags) and labels (<label>). I then simply added another field to the existing form field set:

  • And that’s it already. I immediately noticed the difference and have not received any new spam since. Let me know how you solved the issue. Also, post to the comments if you have problems following the instructions and I’ll try to help!

    No comments yet.

    Leave a Reply