Wednesday, September 4, 2013

Very Simple PHP Captcha

Very Simple PHP Captcha :
Very easy and it requires only a couple lines of code. Please follow the below steps.

Step 1
The first step is to create a HTML form which is later submitted.
I assume you already have a HTML form, so I'll only focus on the captcha code and not all the other fields.
 
<?php
session_start();
echo '<form action="something.php" method="post">';
$rand_int1 = substr(mt_rand(),0,2);
$rand_int2 = substr(mt_rand(),0,1);
$rand_int3 = substr(mt_rand(),0,1);
$captcha_answer = $rand_int1 + $rand_int2 - $rand_int3;
$_SESSION['captcha_answer'] = $captcha_answer;
echo 'What is '.$rand_int1.' + '.$rand_int2.' - '.$rand_int3.'?<br>
<input type="text" name="captcha">
<input type="submit" value="Do captcha">
</form>';
?>


Step 2
The second step is collecting the form data and check if captcha is correct.
 
<?php
session_start();
$captcha = $_POST['captcha'];
$captcha_answer = $_SESSION['captcha_answer'];
 
if($captcha != $captcha_answer) {
    echo 'Captcha is incorrect!';
}
else {
    echo 'Captcha is correct, congratulations! :)';
}
?>


Thanks : ITDB

No comments:

Post a Comment