There are lots of free Captcha modules available on the net which you can simply plug into your website, but if you want to create your own, here is one simple process to create using PHP. Basic concept for Captcha is to reduce or stop spam on your website, Captcha prevents from spam as it force the user to type the exact letters or answer that is generated using some alorigthm before submitting the forms. A common type of Captcha requires the user type letters or digts as that appears on the screen. Today, we are going to build a very simple Captcha using PHP.
Firstly, we will create a random text using php functions and then encrypt it using md5(). Once we get the number we will reduce it to 5 letter string to make it short and user friendly.
< ? php
//Start the session
session_start();
//Generating string using php functions and then encrypt it
$stringValue = md5(microtime() * mktime());
//Lets take just 5 letters from the whole string
$finalString = substr($stringValue,0,5);
? >
Secondly, we will write the string on to the image.
< ? php
$captcha = imagecreatefrompng("./captcha.png");
/*
Set colours to display,
you can select different colours depending upon your website templates
*/
$black = imagecolorallocate($captcha, 0, 0, 0);
$line = imagecolorallocate($captcha,233,239,239);
imageline($captcha,0,0,39,29,$line);
imageline($captcha,40,0,64,29,$line);
? >
Finally, writing the text to image using imagestring() function.
< ? php
imagestring($captcha, 5, 20, 10, $finalString, $black);
/*
lets encrypt the string and store in session key
*/
$_SESSION['key'] = md5($finalString);
/*
Print the image in the form
*/
? >
< form... method="post" action="myform.php">
Insert text as seen below:<... input type="textbox" name="code" />
< ? php
header("Content-type: image/png");
imagepng($captcha);
? >
<.. input type="submit" />
Now, we need to confirm that user have inserted the string correctly once the form is submitted.
< ? php
session_start();
//Now we will encrypt the value inserted by user and then compare
if(md5($_POST['code']) != $_SESSION['key'])
{
die("Error: Sorry the verification does not match.");
}else{
echo 'Verification Successful.';
}
? >
Thursday, July 15, 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment