Krysvac
Krysvac

Reputation: 67

PHP compare values not working

i have a form that i've made a custom security question for. It randomizes a question with the code

$rand1 = rand ( 1,20 );
$rand2 = rand ( 1,20 );
$randsvar = $rand1 + $rand2;
$securefråga = "Vad blir " . $rand1 . "+" . $rand2;

and i then parse it in to my code as

$_POST["secure"]

after that i convert them both to integers and compare both the converted $randsvar and the form value with eachother with the code

$intSecure = intval($secure);
$intRand = intval($randsvar);
if($intSecure == $intRand)
{
  $errorNummer++;
}
else
{
  $secureErr = "wrong answer";
}

however even if i type the correct answer it gives me the error message, what am i doing wrong?

Upvotes: 0

Views: 61

Answers (1)

Kevin
Kevin

Reputation: 41893

You can use sessions to save the current operation. If submitted, compare the user input to the saved session total. Rough example:

if(!isset($_POST['submit'])) {
    $_SESSION['rand1'] = rand(1, 20);
    $_SESSION['rand2'] = rand(1, 20);
    $_SESSION['randsvar'] = $_SESSION['rand1'] + $_SESSION['rand2'];
} else {
    $input = $_POST['input'];
    if($input == $_SESSION['randsvar']) {
        echo 'correct';
    } else {
        echo 'incorrect';
    }
    exit;
}

?>

<form method="POST">
    <label>
        <?php echo $_SESSION['rand1'] . ' + ' . $_SESSION['rand2'] . ' = '; ?>
        <input type="text" name="input" />
        <input type="submit" name="submit" />
    </label>
</form>

Upvotes: 1

Related Questions