PHP CAPTCHA


PHP Captcha use to protect from Web Forms.

Example :
In this example,we create one captcha.php and index.php.
captcha.php
<?php
session_start();
$ranStr = md5(microtime());
$ranStr = substr($ranStr, 0, 6);
$_SESSION['cap_code'] = $ranStr;
$img = imagecreatefromjpeg("captcha.jpg");
$color = imagecolorallocate($img, 0, 0, 0);
imagestring($img, 5, 5, 5, $ranStr, $color);
header("Content-type: image/jpeg");
imagejpeg($img);
?>

index.php
<?php
session_start();
$cap = 'not'; // This php variable is passed to jquery variable to show alert
if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{
if ($_POST['captcha'] == $_SESSION['cap_code']) 
{
// Captcha verification is Correct. Do something here!
$cap = 'yes';
echo "Thankyou";
} 
else 
{
echo "wrong ";
$cap = '';
}
}
?>
<html>
<body>
<form action="" method="post">
<label>Name:</label><br/>
<input type="text" name="name" id="name"/><br>
<label>Message:</label><br/>
<textarea name="msg" id="msg"></textarea><br>
<label>Enter the contents of image</label><br>
<input type="text" name="captcha" id="captcha" /><br>
<img src='captcha.php' /><br><br>
<input type="submit" value="Submit" id="submit"/><br>
</form>
<div class="cap_status"></div>
</body>
</html>
			
Output :
Captcha image