PHP Simple CAPTCHA CODE using SESSION


Create this file :

eg : captcha.php

<?php
session_start();
$ranStr = md5(microtime());
$ranStr = substr($ranStr, 0, 6);
$_SESSION[‘cap_code’] = $ranStr;
$newImage = imagecreatefromjpeg(“cap_bg.jpg”);
$txtColor = imagecolorallocate($newImage, 00, 0);
imagestring($newImage, 555, $ranStr, $txtColor);
header(“Content-type: image/jpeg”);
imagejpeg($newImage);
?>

FORM like this

<form action=”” method=”post”>
<label>Name:</label><br/>
<input type=”text” name=”name” id=”name”/>
<label>Message:</label><br/>
<textarea name=”msg” id=”msg“></textarea>
<label>Enter the contents of image</label>
<input type=”text” name=”captcha” id=”captcha” />
<img src=’captcha.php’ />
<input type=”submit” value=”Submit” id=”submit”/>
</form>

ACTION PAGE : 

<?php
if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’)
{
if ($_POST[‘captcha’] == $_SESSION[‘cap_code’]) 
{
// Captcha verification is Correct. Do something here!
}
else 
{
// Captcha verification is wrong. Take other action
}
}
?>

Thank you.