PHP Captcha using jQuery AJAX

by Vincy. Last modified on October 7th, 2022.

Captcha code in a form is used for ensuring that the form is submitted with manual intervention without any tools or programs. In the previous tutorial, we have seen how to add captcha in PHP.

In this tutorial, we are using jQuery AJAX for getting captcha image from PHP. Using jQuery we can also refresh the captcha code by resending AJAX call to generate new captcha image.

View Demo

Contact Form with Captcha

This code is for displaying contact form with refreshable captcha image.

captcha contact

<html>
<head>
<title>PHP Captcha using jQuery AJAX</title>
<link rel="stylesheet" type="text/css" href="assets/css/styles.css" />
<script type="text/javascript" src="assets/js/captcha-contact.js"></script>
<script src="https://code.jquery.com/jquery-3.6.1.min.js"
    integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ="
    crossorigin="anonymous"></script>
</head>
<body>
    <div id="frmContact">
        <div id="mail-status"></div>
        <div>
            <label style="padding-top: 20px;">Name</label> <span
                id="userName-info" class="info"></span><br /> <input
                type="text" name="userName" id="userName"
                class="demoInputBox">
        </div>
        <div>
            <label>Email</label> <span id="userEmail-info" class="info"></span><br />
            <input type="text" name="userEmail" id="userEmail"
                class="demoInputBox">
        </div>
        <div>
            <label>Subject</label> <span id="subject-info" class="info"></span><br />
            <input type="text" name="subject" id="subject"
                class="demoInputBox">
        </div>
        <div>
            <label>Content</label> <span id="content-info" class="info"></span><br />
            <textarea name="content" id="content" class="demoInputBox"
                cols="60" rows="6"></textarea>
        </div>
        <div>
            <label>Captcha</label> <span id="captcha-info" class="info"></span><br />
            <input type="text" name="captcha" id="captcha"
                class="demoInputBox"> <img id="captcha_code"
                src="captcha_code.php" /><br> <a name="submit"
                class="btnRefresh" onClick="refreshCaptcha();">Refresh
                Captcha</a>
        </div>
        <br>
        <button name="submit" class="btnAction" id="btn-login-submit"
            onClick="sendContact();">Send</button>
        <div id="loader-icon">
            <img src="loader.gif" />
        </div>
    </div>
</body>
</html>

We have same validation script as we have seen in jQuery contact form tutorial. So, the following code shows only the validation of the captcha field.

function validateContact() {
	var valid = true;
	$(".demoInputBox").css('background-color', '');
	$(".info").html('');

	if (!$("#userName").val()) {
		$("#userName-info").html("(required)");
		$("#userName").css('background-color', '#FFFFDF');
		valid = false;
	}
	if (!$("#userEmail").val()) {
		$("#userEmail-info").html("(required)");
		$("#userEmail").css('background-color', '#FFFFDF');
		valid = false;
	}
	if (!$("#userEmail").val().match(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/)) {
		$("#userEmail-info").html("(invalid)");
		$("#userEmail").css('background-color', '#FFFFDF');
		valid = false;
	}
	if (!$("#subject").val()) {
		$("#subject-info").html("(required)");
		$("#subject").css('background-color', '#FFFFDF');
		valid = false;
	}
	if (!$("#content").val()) {
		$("#content-info").html("(required)");
		$("#content").css('background-color', '#FFFFDF');
		valid = false;
	}
	if (!$("#captcha").val()) {
		$("#captcha-info").html("(required)");
		$("#captcha").css('background-color', '#FFFFDF');
		valid = false;
	}

	return valid;
}

jQuery Captcha Refresh

This simple jQuery script will refresh PHP captcha code and recreate the image with the new code. This new image will be set as captcha image source.

function refreshCaptcha() {
	$("#captcha_code").attr('src', 'captcha_code.php');
}

function sendContact() {
	var valid;
	valid = validateContact();
	if (valid) {
		$("#loader-icon").show();
		$("#btn-login-submit").hide();
		jQuery.ajax({
			url: "contact-mail.php",
			data: 'userName=' + $("#userName").val() + '&userEmail=' + $("#userEmail").val() + '&subject=' + $("#subject").val() + '&content=' + $("#content").val() + '&captcha=' + $("#captcha").val(),
			type: "POST",
			success: function(data) {
				$("#mail-status").html(data);
				$("#loader-icon").hide();
			},
			error: function() {
				$("#loader-icon").hide();
			}
		});
	}
}

PHP Captcha Image Creation

In PHP we are using PHP rand() to generate a random number. This random number will be encrypted by using md5() and cropped into 6 character captcha code.

Then this code will be added to PHP session and as a source of captcha image by using PHP GD functions.

captcha_code.php

<?php
session_start();
$random_alpha = md5(rand());
$captcha_code = substr($random_alpha, 0, 6);
$_SESSION["captcha_code"] = $captcha_code;
$target_layer = imagecreatetruecolor(70, 30);
$captcha_background = imagecolorallocate($target_layer, 255, 160, 119);
imagefill($target_layer, 0, 0, $captcha_background);
$captcha_text_color = imagecolorallocate($target_layer, 0, 0, 0);
imagestring($target_layer, 5, 5, 5, $captcha_code, $captcha_text_color);
header("Content-type: image/jpeg");
imagejpeg($target_layer);
?>

PHP validation of the captcha code with session

This PHP script validates the captcha code posted via the contact form.

If the captcha code post data is empty or not valid, then it returns the error response to the UI.

The captcha validation is made by comparing the post data with the PHP sessions. A PHP session index that contains the last generated captcha code for doing this validation on the form submission.

contact-mail.php

<?php
session_start();
if ($_POST["captcha"] == $_SESSION["captcha_code"]) {
    $toEmail = "admin@phppot_samples.com";
    $mailHeaders = "From: " . $_POST["userName"] . "<" . $_POST["userEmail"] . ">\r\n";
    if (mail($toEmail, $_POST["subject"], $_POST["content"], $mailHeaders)) {
        print "<p class='success'>Contact Mail Sent.</p>";
    } else {
        print "<p class='Error'>Problem in Sending Mail.</p>";
    }
} else {
    print "<p class='Error'>Enter Correct Captcha Code.</p>";
}
?>

View DemoDownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

↑ Back to Top

Share this page