imgIn this tutorial ”  PHP Captcha Image Verification Tutorial” One of the best ways is to use an image verification, called as captcha. What it does is to dynamically create an image with a random string displayed on it. Then visitor is asked to type that string in a text field and once the form is submitted it checks if the string on the image matches the one inputted by the user.

Because there is no easy way to read a text from an image (image recognition) this is a good way to protect your web forms from spammers. For doing this CAPTCHA , the most recommended thing is use session variable where it stores the strings generated and displayed on the dynamic images.

So let’s start with our Session Variable:

captcha.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
session_start();
$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);
?>

The above script is to generate a random number from 10000 to 99999 and then assign it to $_SESSION[‘vercode’]. Then it generates a 25×65 pixels image with black background and white text using size 14. So if you upload that session.php file on your web site and open http://www.site.com/session.php you will see an image displaying random integer. You will receive a new random integer every time when you refresh the page.

HTML_Web Form:

To add the Inputs,lets create a simple web form

1
2
3
4
5
<form action="submit.php" method="post">
Comment: <textarea name="coment"></textarea>
Enter Code <img src="captcha.php"><input type="text" name="vercode" />
<input type="submit" name="Submit" value="Submit" />
</form>

Submit.php

Final Step is to create a submit.php script which will check if the verification code you enter matches the one that has been randomly generated.

1
2
3
4
5
6
7
8
9
10
<?php
session_start();
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>';
};
?>

Conclusion

Now you know how to add Captcha verification for your web forms.Download the source code to play with it.

One thought on “PHP Captcha Image Verification Tutorial

Leave a Reply

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