PHP表单验证(有点像captcha)


PHP form validation (sort of like captcha)

我已经用我能想到的一切方法尝试过了,有一个包含3组数据的多维数组,每组都有一个问题和相应的awswer,我想验证用户对每个问题的回答。

问题是,当我按下提交按钮时,用户实际上正在提交下一个问题的答案,只有按下提交按钮才能显示!这可以通过输入一个期望值(如"2")来验证,并等待下一个问题为1+1=

<?php
$question = array(
    0 => array(
        'question' => "1+1=",
        'answer' => 2
        ),
    1 => array(
        'question' => "2+1=",
        'answer' => 3
        ),
    2 => array(
        'question' => "4+1=",
        'answer' => 5
        )
);
$arrayIndex = array_rand($question);
$q = $question[$arrayIndex]['question'];
$a = $question[$arrayIndex]['answer'];
if (isset($_POST['submit'])) {
    if($_POST['answer'] == $a) {
        echo "correct";
    } else {
        echo "incorrect";
    }
} else {
    echo "Answer this:";
}
print $a;
print ("
<form method='post'><br/>
<input type='text name='". $a ."' value='". $q ."'>
<input type='text' name='answer'><br/>
<input type='submit' name='submit'><br/>
</form>
");
?>

问题是您的条件检查无效。条件中的$a被设置为一个新值,因此包含新答案,而不是用户提交的问题的答案。

我明确添加了一个隐藏属性来捕获问题的索引,然后相应地检查答案。

代码当然可以进行优化和清理,但这里有一个简单的代码修改来完成任务。

<?php
$question = array(
    0 => array(
        'question' => "1+1=",
        'answer' => 2
        ),
    1 => array(
        'question' => "2+1=",
        'answer' => 3
        ),
    2 => array(
        'question' => "4+1=",
        'answer' => 5
        )
);
if (isset($_POST['submit'])) {
    if($_POST['answer'] == $question[$_POST['index']]['answer']) {
        echo "correct";
    } else {
        echo "incorrect";
    }
} else {
    echo "Answer this:";
}
$arrayIndex = array_rand($question);
$q = $question[$arrayIndex]['question'];
$a = $question[$arrayIndex]['answer'];

print $a;
print ("
<form method='post'><br/>
<input type='text name='". $a ."' value='". $q ."'>
<input type='hidden' name='index' value='".$arrayIndex."'>
<input type='text' name='answer'><br/>
<input type='submit' name='submit'><br/>
</form>
");
?>