February 22, 2024 5:02 am

How to create CAPTCHA image verification in PHP and jQuery

Captcha is the simple verification on your web forms that the user is a human or a computer. Its used to prevent spammers on your website. If you use captcha on your web forms its hard for spam bots to submit data to web site. The reason to write this tutorial is to demonstrate how to create captcha image in your application using PHP and jQuery.

CAPTCHA image verification in PHP and jQuery

[wpdm_file id=61]DEMO

We have used Fonts to generate text and create a random alpha-numeric word with background texture to prevent OCR readers. Used GD library to generate images.

index.php

File contains PHP code to load captcha image and text box to input visible word.

<?php
// Session start must be the first line, whether you include it or not :) 
session_start(); 
if(empty($_POST))
{
    echo '<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
   <script type="text/javascript">
$(document).ready(function(){
$("#new").click(function() {
$("#captcha").attr("src", "captcha.php?"+Math.random());
});    
});
</script> 
<form method="post" action="index.php"> 
<span style="float: left;margin-top: 7px;margin-right:10px;">CAPTCHA Code:</span>
<img src="captcha.php" border="0" alt="CAPTCHA!" id="captcha"><a href="#new" id="new"><img src="reload.png" style="width: 35px;margin-left:10px;" /></a>
<br /> 
Enter CAPTCHA: <input type="text" name="key" value="" /> 
<br /><br /> 
<input type="submit" value=" Verify Captcha " /> 
</form>';
}
else
{
    if(strlen($_SESSION['key']) && $_POST['key'] == $_SESSION['key'])
    {
        echo "Captcha Verified!!!";
    }
    else
    {
        echo "Invalid Captcha.... <a href='index.php'>try again</a>";
    }
}
?>

HTML is mixed to show image and input box and accept post data on the same page to verify. Create session of given captcha word once you submit that word it check that word with saved session word. Include jQuery library to reload captcha image onClick event $(“#captcha”).attr(“src”, “captcha.php?”+Math.random()); this line change src of visible image captcha.php generate captcha image every time it generate random word.

if(strlen($_SESSION['key']) && $_POST['key'] == $_SESSION['key'])

Check submitted word if match then show valid else invalid.

captcha.php

File contains PHP Code to generate captcha image.

<?php 
session_start(); 

class CaptchaSecurityImages { 
  /* select the type of font, must be used in directoy in which script is being called into */ 
  var $font = 'CALIBRI.TTF'; 

  function generateCode($characters) { 
    $possible = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; 
    $possible = $possible.$possible.'2345678923456789'; 
    $code = ''; 
    $i = 0; 
    while ($i < $characters) {  
      $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1); 
      $i++; 
    } 
    return $code; 
  } 

  function CaptchaSecurityImages($width = 145,$height = 35, $characters = 6) { 
    $code = $this->generateCode($characters); 
    $font_size = $height * 0.60; 
    $image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream'); 

    /* set the colours */ 
    $bgR = mt_rand(0, 255); $bgG = mt_rand(0, 255); $bgB = mt_rand(0, 255); 
    $background_color = imagecolorallocate($image, $bgR, $bgG, $bgB); 
    $noise_color = imagecolorallocate($image, abs(100 - $bgR), abs(100 - $bgG), abs(100 - $bgB)); 
    $text_color = imagecolorallocate($image, abs(255 - $bgR), abs(255 - $bgG), abs(255 - $bgB)); 

    /* generate random dots in background */ 
    for($i = 0; $i < ($width*$height) / 3; $i++) { 
      imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color); 
    } 

    /* generate random lines in background */ 
    for($i = 0; $i < ($width*$height) / 150; $i++) { 
      imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color); 
    } 

    /* set random colors */ 
    $w = imagecolorallocate($image, abs(100 - $bgR), abs(100 - $bgG), abs(100 - $bgB)); 
    $r = imagecolorallocate($image, abs(100 - $bgR), abs(100 - $bgG), abs(100 - $bgB)); 

    /* Draw a dashed line, 5 red pixels, 5 white pixels */ 
    $style = array($r, $r, $r, $r, $r, $w, $w, $w, $w, $w); 
    imagesetstyle($image, $style); 
    imageline($image, 0, 0, $width, $height, IMG_COLOR_STYLED); 
    imageline($image, $width, 0, 0, $height, IMG_COLOR_STYLED); 

    /* create random polygon points */ 
    $values = array( 
        mt_rand(0, $width), mt_rand(0, $height), 
        mt_rand(0, $height), mt_rand(0, $width), 
        mt_rand(0, $width), mt_rand(0, $height), 
        mt_rand(0, $height), mt_rand(0, $width), 
        mt_rand(0, $width), mt_rand(0, $height), 
        mt_rand(0, $height), mt_rand(0, $width), 
        mt_rand(0, $width), mt_rand(0, $height), 
        mt_rand(0, $height), mt_rand(0, $width), 
        mt_rand(0, $width), mt_rand(0, $height), 
        mt_rand(0, $height), mt_rand(0, $width), 
        mt_rand(0, $width), mt_rand(0, $height), 
        mt_rand(0, $height), mt_rand(0, $width),); 

    /* create Random Colors then set it to $clr */ 
    $r = abs(100 - mt_rand(0, 255)); 
    $g = abs(100 - mt_rand(0, 255)); 
    $b = abs(100 - mt_rand(0, 255)); 
    $clr = imagecolorallocate($image, $r, $g, $b); 

    /* create filled polygon with random points */ 
    imagefilledpolygon($image, $values, 6, $clr); 

    $textbox = imagettfbbox($font_size, 0, $this->font, $code) or die('Error in imagettfbbox function'); 
    $x = ($width - $textbox[4])/2; 
    $y = ($height - $textbox[5])/2; 
    imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext function'); 

    /* pretty it */ 
    imageantialias($image, 100); 
    imagealphablending($image, 1); 
    imagelayereffect($image, IMG_EFFECT_OVERLAY); 

    /* output captcha image to browser */ 
    header('Content-Type: image/jpeg'); 
    imagejpeg($image); 
    imagedestroy($image); 
    $_SESSION['key'] = $code; 
  } 
} 

$captcha = new CaptchaSecurityImages(145, 35, rand(4, 6)); 

?>

This file create image with random string and show in png format on form $captcha = new CaptchaSecurityImages(145, 35, rand(4, 6)); width and height given with random number of latter here we select 4,6 it randomly show 4-6 latter captcha.

Hope you found this tutorial helpful please comment your views and problem faced in configuration.

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

9 responses to “How to create CAPTCHA image verification in PHP and jQuery”

  1. saltun says:

    #new 🙁 🙁 return false; 🙂 🙂

  2. Shahbaz Ahmed Bhatti says:

    COOOOOOOOOOOOOL i understoood how it work. Let me implement in my form

  3. Anant says:

    when i insert data in data base by admin side then webpage auto update without any event effect how it is possible
    like facebook,yahoo criket score without page refresh it show new post/and live score

  4. malves says:

    In my project the image did not appear

  5. gabrouze says:

    You can open in a dialog box the following code to ear the captcha :

    <source src="http://translate.google.com/translate_tts ? tl=en&q=” type=”audio/mp3″ />
    <source src="http://translate.google.com/translate_tts ? tl=en&q=” type=”audio/ogg” />
    Your browser does not support the audio tag.

  6. Zalak Thakkar says:

    Hello,
    Nice tutorial.
    But i have an issue when i reload the captcha. It’s not reloading the captcha image.

  7. lay says:

    does anyone know how to build a google like recaptcha

  8. lay says:

    does anyone know how to build a google like recaptcha

  9. Anant Jain says:

    Nice, but i would like to know that how can i change background image ?

Leave a Reply

Your email address will not be published. Required fields are marked *