| 1 comments ]

CAPTCHAs are used to prevent automated software from performing actions.CAPTCHAs have several applications for practical security, including Preventing Comment Spam in Blogs, Preventing Comment Spam in Blogs,CAPTCHAs also offer a plausible solution against email worms and spam.

The following is an example for securing a form with captcha

main.php

<?php

require_once('functions.php');

If($_POST){

If(validate_captcha()){

echo "captcha okay";

//do your actions here

else{

echo " captcha not okay";

}

}

}else{

mt_srand ((double)microtime()*1000000);

$maxran = 1000000;

$random = mt_rand(0, $maxran);

$html = "<html>

<header><title>form with captcha</title></header>

<body> <form name='frm' action='' method='post'>";

$html.="name:<input type='text' name='txtname'>";

$html.="password:<input type='password' name='txtpwd'>";

$html .= "<div id=\"Registercode\"><table><tr><td><img src='". create_captchaImg.php?ran=".$random." ></td> ";

$html .= "<td><input type=\"text\" name=\"captchacode\" maxlength=\"10\" /></td></tr></table></div>";

$html .= "<input type='hidden' name='randomcode' value='". $random."'>

<input type='submit' name='submitbtn' value='submit' >

</form>

";

echo $html;

}

?>

functions.php

<?php

/* function to generate captcha code */

function generate_captcha($num) {

$timemd5=md5($num);

$date = date('F j');

$year=date('Y');

$temp=md5($num . $date.$year . $timemd5);

$capcode = hexdec($temp);

$code = substr($capcode, 4, 6);

return $code;

}

/* function to validate captcha*/

function validate_captcha() {

$captchacode = $_POST['captchacode'];

$randomcode = $_POST['randomcode'];

$generated_code = generate_captcha($randomcode);

$valid = false;

if ((trim($captchacode) != "") && (strcmp($captchacode, $generated_code) == 0))

$valid = true;

else

$valid=false;

return $valid;

}

?>

create_captchaImg.php

<?php

/* function to generate captcha image with the captcha code.choose some image as background */

require_once('functions.php');

$ccode=$_REQUEST['ran'];

$capcode = $ccode;

$code = generate_captcha($capcode);

$image = ImageCreateFromJPEG("images/captchabg.jpeg");//give captcha background image path

$text_color = ImageColorAllocate($image, 80, 80, 80);

Header("Content-type: image/jpeg");

ImageString ($image, 5, 12, 2, $code, $text_color);

ImageJPEG($image, '', 75);

ImageDestroy($image);

}

?>

1 comments

phpfrnd said... @ Saturday, August 1, 2009 at 8:57:00 AM GMT+1

Thanks for your valued time for writing this informative blog :)

Post a Comment

Please put your comments here. your questions, your suggestions, also what went wrong with me.