Spam is an absolute nuisance - especially when you receive repetitive contact form submissions regarding a product or service you have no interest in. This simple guide will help you get rid of spammers who submit rubbish through your website contact forms. Google reCaptacha is the answer to your problems 🙂

Step 1

Register a free account with Google reCaptcha here

Step 2

Include the following reCaptcha script just before the tag:

<script src='https://www.google.com/recaptcha/api.js'></script>

Step 3

Include the following code where you would like the reCaptacha box to display:

<div class="g-recaptcha" data-sitekey="YOUR-SITE-KEY-HERE"></div>

Please make sure the site key you insert here is NOT the secret one. The secret one is placed in the PHP file.

Step 4

Validate the reCaptacha code in PHP:

contact.php

<?php

$emailTo = 'curt@base64.co.za';
$emailFrom = 'info@base64.co.za';

$name = $_POST['contactName'];
$email = $_POST['contactEmail'];
$message = $_POST['contactMessage'];

$subject = "Base 64 Community Submission";

$body = "Name: $name \n\nEmail: $email \n\nMessage: $message";
$headers = 'From: ' .' <'.$emailFrom.'>' . "\r\n" . 'Reply-To: ' . $email;

if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {
       $captcha=$_POST['g-recaptcha-response'];
       $secret = "YOUR-SECRET-KEY-HERE";

    $verify = curl_init();
    curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
    curl_setopt($verify, CURLOPT_POST, true);
    curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($verify);
    curl_close($verify);

    $responseData = json_decode($response);

    if($responseData->success) {

        mail($emailTo, $subject, $body, $headers);

        $response_array['status'] = 'success';
        $response_array['recaptchaStatus'] = 'recaptchaSuccess';
        echo json_encode($response_array);

    } else {
        $response_array['status'] = 'success';
        $response_array['recaptchaStatus'] = 'recaptchaError';
        echo json_encode($response_array);
    }

}

?>

Step 5

Now you can validate the response returned by php file in your Javascript:

contact.js

$.ajax({
    type: "POST",
    dataType: 'json',
    url: 'contact.php',
    data: theForm.serialize(),
    success: function (data) {
        if (data.recaptchaStatus == "recaptchaSuccess") {
            $("#recaptchaSuccessDiv").fadeIn(1000, function () {
            $('#recaptchaSuccessDiv').fadeOut(7000);
            });
        } else if (data.recaptchaStatus == "recaptchaError") {
            $("#recaptchaErrorDiv").fadeIn(1000, function () {
            $('#recaptchaErrorDiv').fadeOut(7000);
            });
        }
    }
});