Sunday, January 9, 2011

captcha code with PHP

This is php script used to generate the captcha message.


somcaptcha.php:
---------------


<?php
session_start();
$ranStr = md5(microtime());
$ranStr = substr($ranStr, 0, 6);
$_SESSION['cap_code'] = $ranStr;
$newImage = imagecreatefromjpeg("somecapimg.jpg");
$txtColor = imagecolorallocate($newImage, 0, 0, 0);
imagestring($newImage, 5, 5, 5, $ranStr, $txtColor);
header("Content-type: image/jpeg");
imagejpeg($newImage);
?>

Now we need to validate the generated capatcha code with information submitted in user.



<?php
session_start();
$cap = 'notEq'; // storing the value in a php variable to jquery variable to show alert for quick debugging.
if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{
if ($_POST['captcha'] == $_SESSION['cap_code']) 
{
// Captcha verification is Correct. PRoceed further
$cap = 'Eq';
else 
{
// Captcha verification is wrong. Take other action
$cap = '';
}
}
?>




<html>
<body>
<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='somecaptcha.php' />
<input type="submit" value="Submit" id="submit"/>
</form>
<div class="cap_status"></div>
</body>
</html>


you can add more validations at client side .

2 comments:

  1. Nice post, also congrats for being Tweeted by Smashing Magazine with this post.
    Check it out: Captcha Code

    ReplyDelete
  2. Thanks a lot .
    I could not find the tweet, feel a lot a happy though.

    ReplyDelete

subversion video