Tuesday, January 12, 2010

Captcha using php


<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.

<?php
session_start();
$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.

<?php
$LineColor = imagecolorallocate($NewImage,233,239,239);
$TextColor = imagecolorallocate($NewImage, 255, 255, 255);
imageline($NewImage,1,1,40,40,$LineColor);
imageline($NewImage,1,100,60,0,$LineColor);
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.

<?php
$_SESSION['key'] = $ResultStr;
?>
The resultant random number [trimmed one], carry through session especially for validation purpose.

<?php
header(“Content-type: image/jpeg”);
imagejpeg($NewImage);
?>
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.

<?php
if(isset($_REQUEST['Submit'])){
$key=substr($_SESSION['key'],0,5);
$number = $_REQUEST['number'];
if($number!=$key){
echo ‘ Validation string not valid! Please try again!’;}
else{
echo ‘ Your string is valid!’;}
}
?>

No comments: