PHP Rand()在数学游戏中重置

时间:2014-06-10 10:59:31

标签: php math random

我正在使用PHP的Rand()函数生成两个可以与用户进行比较的随机数,如果用户的答案等于(第一个随机数+第二个随机数),则回显成功消息。但是,我遇到了问题。

我怀疑每次表单POSTED和输入被收集时表单都会重新生成数字,所以我尝试使用会话来保持这些数字的持久性。至少可以说是一团糟。

我找到了这个现有帖子:Problems with guess a number game,但解决方案并没有解决我的问题。

    <?php
        if(empty($_POST)) 
        {
            $_SESSION['$number1'] = Rand(0, 100);
            $_SESSION['$number2'] = Rand(0, 100);
        }

        if($_POST["submit"])
        {
            $input = $_POST['input'];

            if($input == ($_SESSION['$number1'] + $_SESSION['$number2']))
            {
                echo "Correct! ";
            }
            else
            {
                echo "Incorrect! ";
            }
        }

        echo "<hr><br> What is... <b>" . $_SESSION['$number1'] . " + " . $_SESSION['$number2'] . "</b>";
    ?>

    <form action="" method="post">
        <input type="text" name="input">
        <input type="submit" name="submit">
    </form>

<?php
    echo "<b>DEBUG ANSWER: </b> " . ($_SESSION['$number1'] + $_SESSION['$number2']);
?>

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

我改变了一些事情,就个人而言,我不会使用会话,而是用户隐藏的输入。 (如果你担心安全......你不应该......数字游戏,而不是银行网站)

<?php
//Create a function to generate the random numbers (So we can re-use it)
function generateNumbers()
{
    $one = Rand(0, 100);
    $two = Rand(0, 100);
    //Now return the random numbers
    return array('number1' => $one, 'number2' => $two);
}

//Check if the submit button has been clicked
if($_POST["submit"])
{
    $input = $_POST['input'];

    if($input == $_POST['number1'] + $_POST['number2'])
    {
        echo "Correct! ";
    }
    else
    {
        echo "Incorrect! ";
    }
}

//Now we create the numbers
$numbers = generateNumbers();

echo "<hr><br> What is... <b>" . $numbers['number1'] . " + " . $numbers['number2'] . "</b>";
?>

    <form action="" method="post">
        <input type="text" name="input">
        <input type="submit" name="submit">
        <!-- Personally I would rather use hidden inputs, than use the session -->
        <input type="hidden" name="number1" value="<?php echo $numbers['number1'] ?>" />
        <input type="hidden" name="number2" value="<?php echo $numbers['number2'] ?>" />
    </form>

<?php
echo "<b>DEBUG ANSWER: </b> " . ($numbers['number1'] + $numbers['number2']);
?>