Stop spam through my website – Google reCaptcha

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=''></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:



$emailTo = '';
$emailFrom = '';

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

$subject = "Base 64 Community Submission";

$body = "Name: $name nnEmail: $email nnMessage: $message";
$headers = 'From: ' .' <'.$emailFrom.'>' . "rn" . 'Reply-To: ' . $email;

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

    $verify = curl_init();
    curl_setopt($verify, CURLOPT_URL, "");
    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);

    $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:


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