无法获得会话以保存PHP号码

时间:2013-08-17 06:33:33

标签: php session random

我对PHP很新,但我正在尝试制作猜谜游戏。 这个想法是你猜测1-100之间的数字和代码意味着有一个随机分配的代码来猜测,直到猜到,目前只是在分配数字。因此,每当我试图猜测时,它都不会随机化。

<?php
session_start();
$_SESSION[var_answer] = rand (1, 100);
$var_number = $_REQUEST['number'];
if($var_number == $_SESSION[var_answer]){
    echo " That is correct ;)";
}
else if($var_number <0 || $var_number>100){
    echo " Sorry your guess has to be between 0 and 100";
}else if($var_number==" "||$var_number==""){
    echo " Please take a guess first!";
}else if($var_number < $_SESSION[var_answer]){
    echo " Smaller than mine";
}else if($var_number > $_SESSION[var_answer]){
    echo " Larger than mine";
}
echo '<br/><a href="RNGG.php"> return</a>';
?>

到目前为止,这个数字是随机的,但正如我所说,每次会话都没有保存。

2 个答案:

答案 0 :(得分:1)

看看这段代码:

$_SESSION[var_answer] = rand (1, 100);
$var_number = $_REQUEST['number'];
if($var_number == $_SESSION[var_answer]){
    echo " That is correct ;)";
}

每次重新加载页面时都会覆盖会话变量。据我所知,你想在会话中存储号码,直到有人猜到它为止。试试这个:

//put a random number into session, if the variable is not defined
if(!isset($_SESSION['var_answer']))
{
    $_SESSION['var_answer'] = rand (1, 100);
}

$var_number = $_REQUEST['number'];
if($var_number == $_SESSION['var_answer']){
    echo " That is correct ;)";
    //undefine the variable if it's guessed
    unset($_SESSION['var_answer']);
}

答案 1 :(得分:0)

$_SESSION[var_answer]必须在任何地方更改为$_SESSION['var_answer'],它将解决您的问题。 所以你的代码必须是

<?php
session_start();
$_SESSION['var_answer'] = rand (1, 100);
$var_number = $_REQUEST['number'];
if($var_number == $_SESSION['var_answer']){
    echo " That is correct ;)";
}
else if($var_number <0 || $var_number>100){
    echo " Sorry your guess has to be between 0 and 100";
}else if($var_number==" "||$var_number==""){
    echo " Please take a guess first!";
}else if($var_number < $_SESSION['var_answer']){
    echo " Smaller than mine";
}else if($var_number > $_SESSION['var_answer']){
    echo " Larger than mine";
}
echo '<br/><a href="RNGG.php"> return</a>';
?>