Captcha Image Verification

Captcha is a good way to avoid automatic form submission.In this tutorial, I explains about captcha image verification. It creates an image with a random string displayed on it.  Then the user asks to fill the string in the form filed and once form submitted it checks if the string on image matches the input by the user. This is the easiest way to protect web form from spammers.

This file create an image with random string displayed on it.

$text = rand(10000,99999);
$_SESSION["vercode"] = $text;
$height = 25;
$width = 65;
$image_p = imagecreate($width, $height);
$black = imagecolorallocate($image_p, 0, 0, 0);
$white = imagecolorallocate($image_p, 255, 255, 255);
$font_size = 14;
imagestring($image_p, $font_size, 5, 5, $text, $white);
imagejpeg($image_p, null, 80);

This script genrate a random number from 10000 to 99999 and assign it to a session variable $_SESSION[“vercode”]. then it generate a image 25*65 px with balck background and font size 14px. Now create a web form .

<form name="captcha" method="post">
Name :<input type="text" name="name" required="required" />
Email :<input type="email" name="email" required="required" />
Verification code :<input type="text" name="vercode" size="10" required="required" />&nbsp;<img src="captcha.php">
<input type="submit" name="submit" value="Submit" />

Now create php script for submitting the form

if ($_POST["vercode"] != $_SESSION["vercode"] OR $_SESSION["vercode"]=='')  {
     echo  '<strong>Incorrect verification code.</strong>';
} else {
     // add form data processing code here
     echo  '<strong>Verification successful.</strong>';

This code check the verfication code input by user matches with sring given on image. if the code mataches then the form data submit else error message shows

Download Source Code(Captcha Image Verification)
Size: 2.07 KB
Version: V 1.0

Recommended Tutorials for you


Anuj kumar

This is Anuj Kumar. I’m a professional web developer with 5+ years of experience. I write blogs in my free time. I love to learn new technologies and share with others. I founded PHPGurukul in September 2015. The main aim of this website to provide PHP, Jquery, MySQL, PHP Oops and other web development tutorials. .


          1. C my code once
            9 hours ago
            location of css assests/css/style.css
            in style.css make change in this line
            background-image: url(“../images/banner-image-1.jpg”)

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to top button