11th Jan 2010 at 2:12 PM | Posted in PHP CAPTCHA | Leave a comment

Create a form :

<form name=”form1″ method=”post” action=”form.php” “>
<table width=”342″ align=”center” cellspacing=”0″ bgcolor=”#D4D0C8″>
<tr>  <td align=”center”><img src=”php_captcha.php”></td><td align=”center”> Please enter the string shown in the image in the form.<br></td><td align=”center”><input name=”number” type=”text”></td><td><input name=”Submit” type=”submit”   value=”Submit”></td> </tr></table></form>

The <ima src=…> is given a page php_captcha.php. Lets create the page.

The following code use to create random numbers and this number are embedding with existing image file, the first line used to initiate session, which use to carry the user inputs.

$RandomStr = md5(microtime());
$ResultStr = substr($RandomStr,0,5);
$NewImage =imagecreatefromjpeg(“img.jpg”);

The second line [md5 (microtime ())] use to generate the random string, and the resultant string is trim by using third line [substr], which returns the portion of string specified by the start and length parameters.
The function imagecreatefromjpeg (“img.jpg”) is use to create a image by existing image file and as back ground ,so that you need to give an image file path.
$LineColor = imagecolorallocate($NewImage,233,239,239);
$TextColor = imagecolorallocate($NewImage, 255, 255, 255);
imagestring($NewImage, 5, 20, 10, $ResultStr, $TextColor);

After creation of back ground image, we generate some linear line, which is use to avoid the phrasing from random numbers, the respective lines are create by the function named imageline () and imagestring () use to draw a random string horizontally.
$_SESSION[‘key’] = $ResultStr;
The resultant random number [trimmed one], carry through session especially for validation purpose.
header(“Content-type: image/jpeg”);

Finally above two functions are uses to display/out put the image to browser. So we can just call the particular file by through image source path, it will display the final image.

$number = $_REQUEST[‘number’];
echo ‘ Validation string not valid! Please try again!’;}
echo ‘ Your string is valid!’;}


Blog at
Entries and comments feeds.