Nazmul Nazmul - 5 months ago 14
PHP Question

Captcha using mathmatics

I am trying to make a captcha with mathematics, where i took 2 random variable, sum them and match with user input. But when Me/user click on submit button, the value of two variable change and doesn't match with user input. How can i solve this ? any suggestion ?

<?php
$a = rand(1,9);
$b = rand(1,9);
$z = $a + $b;
if(isset($_POST["submit"])){

$captcha = $_POST['captcha'];
if ($captcha != $z){
echo $captcha." and ".$z;
}
else {
echo "true";
}

}
?>

<form class="form-horizontal" method="POST" action="">
<div class="input-group">
<span><?php echo $a."+".$b."= ?"; ?></span>
<input type="text" name="captcha">
</div>
<button name="submit">submit</button>
</form>

Answer

How about keeping the correct result you expect to receive in a session variable? It would be "invisible" to the end user and would allow you to easily cross-check it with the value in $_POST.

Here's what I'm thinking:

<?php
session_start();

if (!isset($_POST['submit'])) {
    $a = rand(1,9);
    $b = rand(1,9);
    $z = $a + $b;

    $_SESSION['captcha_result'] = $z;
} else {
    $z = $_SESSION['captcha_result'];
    unset($_SESSION['captcha_result']);

    $captcha = $_POST['captcha'];

    if ($captcha != $z) {
        echo $captcha . " and " . $z;
    } else {
        echo "true";
    }
    exit; // Don't display the form in case the user is summiting a captcha challenge
}
?>

<form class="form-horizontal" method="POST" action="">
   <div class="input-group">
     <span><?php echo $a."+".$b."= ?"; ?></span>
     <input type="text" name="captcha">
   </div>
     <button name="submit">submit</button>
</form>

You can read more about using sessions here

Comments