Registration form with PHP Captcha

Lets create a simple registration form with HTML5 form field validation and PHP Captcha. On submit this form will validate captcha without page refresh and POST data using jQuery. So both captcha verification and save data to mysql database can be done without page load.

Registration Form

Generating an Image CAPTCHA

The following code will generate an alphanumeric captcha with custom font.
function getRandomWord($len = 5) {
$word = array_merge(range('0', '9'), range('A', 'Z'));
return substr(implode($word), 0, $len);

$ranStr = getRandomWord();
$_SESSION["vercode"] = $ranStr;

$height = 35; //CAPTCHA image height
$width = 150; //CAPTCHA image width
$font_size = 24; //CAPTCHA Font size

$image_p = imagecreate($width, $height);
$graybg = imagecolorallocate($image_p, 245, 245, 245);
$textcolor = imagecolorallocate($image_p, 34, 34, 34);

imagefttext($image_p, $font_size, -2, 15, 26, $textcolor, 
'fonts/mono.ttf', $ranStr);

You can save the above code in captcha.php and call the file in img src tag.
<img src="captcha.php" /><br>

On submit you can call your php file through jQuery to validate your captcha code and save data.

Validate captcha in jQuery without page load

$('#register').submit(function() {

$.post("submit_form.php?"+$("#register").serialize(), { }, function(response){
$(".imgcaptcha").attr("src","demo_captcha.php?_="+((new Date()).getTime()));
    alert("Data Submitted Successfully.")
    alert("wrong captcha code!");
return false;

function clear_form(){


Validate captcha in PHP

if(($_REQUEST['captcha'] == $_SESSION['vercode'])){
  $fname = mysql_real_escape_string($_REQUEST['fname']);
  $lname = mysql_real_escape_string($_REQUEST['lname']);
//Here you can write your sql insert statement. 
  echo 1;
  echo 0;

Demo Download Files Total Downloads: 17632
comments powered by Disqus