Captcha with jQuery, ajax and php


A while ago I came across this guide, as I was searching for some simple captcha implementation for some website. Plain and simple, all clear. The only thing I didn't like too much is the javascript part, for webpages I mainly use jQuery for javascripting, so I wanted to use jquery for ajax functions. Also, including multiple inputs besides captcha code makes javscript more comeplex (please read the comments, near the end) nad that is where jquery comes in handy.

The simplest possible example you can find on http://mihap.si/share/captcha/.

What we need:

1.) HTML code

We will use the simplest html input form, besides captcha input we will also add additional name field to demonstrate multiple input posting. For PHP image generation I will use the code from original guide, as no modifications are made.

HTML code (index.html):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head>
	<title>Captcha test site
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>

<body>

<!-- form -->
<form id="myform" method="post">
	Name:
	<input type="text" name="name"><br>
	Captch code:
	<input type="text" name="userinput"><br>
	Captcha image:
	<img class="captcha" src="captchacreate.php"><br>

	<input type="submit" value="Verify">
</form>

<!-- result holder -->
<div class="result"></div>

</body>
</html>

PHP image generation code (captchacreate.php):

<?php
//Start the session so we can store what the security code actually is
session_start();

//Send a generated image to the browser
create_image();
exit(); 

function create_image()
{
    //Let's generate a totally random string using md5
    $md5_hash = md5(rand(0,999));
    //We don't need a 32 character long string so we trim it down to 5
    $security_code = substr($md5_hash, 15, 5); 

    //Set the session to store the security code
    $_SESSION["security_code"] = $security_code;

    //Set the image width and height
    $width = 100;
    $height = 22;  

    //Create the image resource
    $image = ImageCreate($width, $height);  

    //We are making three colors, white, black and gray
    $white = ImageColorAllocate($image, 255, 255, 255);
    $black = ImageColorAllocate($image, 0, 0, 0);
    $grey = ImageColorAllocate($image, 204, 204, 204); 

    //Make the background black
    ImageFill($image, 0, 0, $white); 

    //Add randomly generated string in white to the image
    ImageString($image, 3, 30, 3, $security_code, $black); 

    //Throw in some lines to make it a little bit harder for any bots to break
    ImageRectangle($image,0,0,$width-1,$height-1,$grey);
    imageline($image, 0, $height/2, $width, $height/2, $grey);
    imageline($image, $width/2, 0, $width/2, $height, $grey);
    //imageline($image, 0, 0, $width, $height, $grey);
    imageline($image, $width, 0, 0, $height, $grey); 

    //Tell the browser what kind of file is come in
    header("Content-Type: image/jpeg"); 

    //Output the newly created image in jpeg format
    ImageJpeg($image); 

    //Free up resources
    ImageDestroy($image);
}
?>

As you can see we create new session variable "security_code", into which we store the captcha code and display the created image on page. The same code must be entered through html user input form and then validated.

2.) jQuery

For jQuery source you can download the latest version on download page, or just include this link in index.html page header:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

Now we have to tell jquery what to do with page – after the form with id myform is submitted, get all the variables, execute the ajax post function and in div result display the result of check.php function, into which we submit the entered variables. Also, we have to reload the image and reset the security_code:

<script type="text/javascript">
$(document).ready(function()
{
$('#myform').submit(function() {
	//get user input and create random number
	var input = ($(this).serialize());
	var rand = Math.random();

	//submit post to check.php and reload image
	$.post('check.php', input, function(data) {
  		$('div.result').html(data);
  		$('img.captcha').attr("src", 'captchacreate.php?' + rand);
	});

	return false;
	});

return false;
});
</script>

3.) PHP verification code

After the form is submitted, we have to check the user entered input against the security_code session variable. If all is ok, we display success and display the entered name – check.php:

<?php
session_start();

//Check if the security code and the session value are not blank
//and if the input text matches the stored text
if ( ($_REQUEST["userinput"] == $_SESSION["security_code"]) && (!empty($_REQUEST["userinput"]) && !empty($_SESSION["security_code"])) ) {
	print '<h1>Input verification ok!</h1>';
	print 'Welcome, '. $_REQUEST['name'];
}
else {
	print '<h1>Input verification failed!</h1>';
}

?>

That is it. You can add more inputs as you like, checkboxes etc, no changes to jquery code is required as .serialize() function will take care of that. Of course the image generation is not good enough, php code must be enhanced to make it unreadable by computers, some hints are on original post, you can also search the web for php image generation.

brm

Your IP Address is:
38.107.179.220

  1. #1 by nome on December 1, 2010 - 11:52

    it did not work! the image captcha does not appear :/

  2. #2 by amit on June 16, 2011 - 15:52

    nome :
    it did not work! the image captcha does not appear :/

  3. #3 by Sonali on September 7, 2011 - 10:56

    It works please look whether the file captchacreate.php gets called correctly.

  4. #4 by jisa on September 29, 2011 - 20:28

    hii

  5. #5 by hola on December 12, 2011 - 21:18

    dsfsdfsfsdsdfsdf

(will not be published)
*