如何获取与文本表单的输入值匹配的两个rand()变量的总值?

时间:2014-08-18 06:03:03

标签: php validation random input

我发现无论何时按下提交按钮,它都会更改rand()的当前值,以及它与我的输入值不匹配的原因。

我想用它来验证我的表单。在用户提交消息之前,他/她必须先回答问题。

这是我的代码:

    <?php 
    session_start();
    $numa  = rand(1,5);
    $numb = rand(0,4);
    $_SESSION['valid_res'] = $numa + $numb;
echo 'Answer this '.$numa . ' + ' . $numb .' = '; 
    ?>

    <form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
        <input type="text" name="input" /><input type="submit" name="submit" value="Submit" />
    </form>

    <?php 
    if(isset($_POST['submit'])){
        if(intval($_POST['input']) != $_SESSION['valid_res']){
            echo 'You enter have entered '. intval($_POST['input']) .' it is wrong answer';
            }else{
                echo 'Congratulations you have entered '. intval($_POST['input']) .' it is the correct answer.';
            }
        }
    ?>

2 个答案:

答案 0 :(得分:0)

您正在覆盖每个页面加载的会话值。仅在首次加载时写入,并使用后续值进行检查 您还必须将会话变量转换为整数形式。 试试这个:

if(!isset($_POST['submit']))
{
    $numa  = rand(1,5);
    $numb = rand(0,4);
    $_SESSION['valid_res'] = $numa + $numb;
    echo 'Answer this '.$numa . ' + ' . $numb .' = '; 
}
else
    if(intval($_POST['input']) != intval($_SESSION['valid_res']))
    {
        ...

答案 1 :(得分:0)

使用!==代替!=。使用以下代码

<?php 
    session_start();
    $numa  = rand(1,5);
    $numb = rand(0,4);
    $_SESSION['valid_res'] = $numa + $numb;
echo 'Answer this '.$numa . ' + ' . $numb .' = '; 
    ?>

    <form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
        <input type="text" name="input" /><input type="submit" name="submit" value="Submit" />
    </form>

    <?php 
    if(isset($_POST['submit'])){
        if(intval($_POST['input']) !==$_SESSION['valid_res']){
            echo 'You enter have entered '. intval($_POST['input']) .' it is wrong answer';
            }else{
                echo 'Congratulations you have entered '. intval($_POST['input']) .' it is the correct answer.';
            }
        }
    ?>

希望这有助于你