PHP – CAPTCHA

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.

Code Example: Download Example

To put the both example.php and php_captcha.php file in same directory
and then save the below image(right click on image and then save image as)

put the image in the same directory where both file exist
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 
?>

======================== End php_captch.php file ========================
 

Post to Twitter Post to Digg Post to Facebook Post to Google Buzz Send Gmail

One Response to PHP – CAPTCHA

  1. avatar
    hellon on November 11, 2011 at 6:31 am

    This script is what i am looking for. Fantastic.

Leave a Reply

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

*