CAPTCHA is image validation standard used to prevent automated form by bad bots. The concept is simple that image can only be readed by humens and can’t be read by computer programs. The script is pretty clean and easy to understand. If you have any doubt free free to drop me an email. You require to enable GD library in your PHP configuration becuase of this script use GD library to generate image on the fly with randomly generated text.

The script code is breakup in three part:

1. Function to generate random code.
2. codegen.php file to produce png image file based on the random code geneerated.
3. Validation idea in the action script.

1. getRandString Function

This function take length of string as parameter and generate string with alphabets and numeric characters of the given length.

2. Image Generater

Image code generater file is fully self documented. If is does not work on your server. Please check GD library on your system by PHPINFO().

<?php
session_start(); //start session to store rand code for validation
$str = “”;
$length = 0;
$str = getRandString(6); // Generate code
$_SESSION[‘securecode’] = $str; //storing random code in session variable

//——————————————————
header (“Content-type: image/png”); //setup document header
$im = @imagecreate (75, 40) or die (“Cannot Initialize new GD image stream”); // Create image instance
$background_color = imagecolorallocate ($im, 255, 255, 255); //setting up image background color. Current: WHITE
$text_color = imagecolorallocate ($im, 233, 14, 91); //setting up image foreground color. Current: PINK
imagestring ($im, 20, 1, 1, $str, $text_color); // $im-image instance, 20-available system font no, 1,1-x,y coordinate,$str=code
imagepng ($im); //setup image type we are going to produce
imagedestroy ($im);
?>

Save the above code as codegen.php file.

3. How to validate.

In your form create a field for user input.

<input type=”text” name=”scode” />

Create an image code and set source file as codegen.php

<image src=”codegen.php” vspace=”1″ align=”top” alt=”Image Validation”>

Validate image as follows

if ($_POST[‘validator’] == $_SESSION[‘securecode’]) {
//

Your form processing code

//
unset($_SESSION[‘rand_code’]); //destroy session variable

Written by Bala Krishna

Bala Krishna is web developer and occasional blogger from Bhopal, MP, India. He like to share idea, issue he face while working with the code.

This article has 1 comments