simple CAPTCHA example in PHP

A CAPTCHA is a challenge response test used on computers to check if the user is human.A common kind of CAPTCHA that is used on websites requires that the visitor type the letters and numbers of a distorted image. This method is based on the fact that is difficult for computers to extract the text from the image while it is very easy for humans.


put a small  image in the same directory where both file exist then the image name must be img.jpg



======= Start example.php file =======
<?php
session_start();
if(isset($_REQUEST['Verify'])){
$key = substr($_SESSION['key'],0,5);
$number = $_REQUEST['number'];
if($number!=$key)
echo '<font color="#FF0000" size=1>Invalid code</font>';
else
echo '<font color="#66CC00" size=1>Valid code</font>';
}
?>

<form name="form1" method="post" action="">
<img src="php_captcha.php"> Please enter the string.<br> <input name="number" type="text">
<input name="Verify" type="submit" value="Verify">
</form

====== End example.php file =======

====== Start php_captch.php file ======

<?php
session_start();

$RandomStr = md5(microtime());// md5 to generate the random string
$ResultStr = substr($RandomStr,0,5);//trim 5 digit
$NewImage =imagecreatefromjpeg("img.jpg");//image create by existing image and as back ground
$LineColor = imagecolorallocate($NewImage,233,239,239);//line color
$TextColor = imagecolorallocate($NewImage, 255, 255, 255);//text color-white
imageline
($NewImage,1,1,40,40,$LineColor);//create line 1 on image
imageline($NewImage,1,100,60,0,$LineColor);//create line 2 on image
imagestring
($NewImage, 5, 20, 10, $ResultStr, $TextColor);// Draw a random string horizontally
$_SESSION
['key'] = $ResultStr;// carry the data through session
header
("Content-type: image/jpeg");// out out the image
imagejpeg
($NewImage);//Output image to browser
?>



No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...