PHP Captcha using jQuery AJAX

by Vincy. Last modified on August 22nd, 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 DemoDownload

Contact Form with Captcha

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


<div id="frmContact">
		<label style="padding-top:20px;">Name</label>
		<span id="userName-info" class="info"></span><br/>
		<input type="text" name="userName" id="userName" class="demoInputBox">
		<span id="userEmail-info" class="info"></span><br/>
		<input type="text" name="userEmail" id="userEmail" class="demoInputBox">
		<span id="subject-info" class="info"></span><br/>
		<input type="text" name="subject" id="subject" class="demoInputBox">
		<span id="content-info" class="info"></span><br/>
		<textarea name="content" id="content" class="demoInputBox" cols="60" rows="6"></textarea>
		<span id="captcha-info" class="info"></span><br/>
		<input type="text" name="captcha" id="captcha" class="demoInputBox"><br>
		<img id="captcha_code" src="captcha_code.php" />
		<button name="submit" class="btnRefresh" onClick="refreshCaptcha();">Refresh Captcha</button>
		<button name="submit" class="btnAction" onClick="sendContact();">Send</button>

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.

if(!$("#captcha").val()) {
	valid = false;

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() {

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.

$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");

View DemoDownload

↑ Back to Top

Share this page