会话

时间:2017-06-09 05:57:43

标签: php session session-variables

我有2页:

的index.php

<?php session_start(); ?>
<!DOCTYPE html>

<html>
<head>
    <title></title>

    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="style.css">

</head>
<body>
    <div class="container">
        <div class="wrapper">
            <h1>Welcome to the Great Number Game!</h1>  
                <h3>I am thinking of a number between 1 and 100</h3>
                <h3>Take a guess!</h3>

<?php

    echo $_SESSION['message'];



?>
                <form method="post" action="process.php">
                    <input type="hidden" name="action" value="guess">
                    <input type="text" name="number">
                    <br>
                    <input type="submit" value="Submit">
                </form>
        </div>
    </div>
</form>
</body>
</html>

和process.php

<?php session_start(); ?>


<?php header('Location: index.php'); ?>

<?php

if (!isset($_SESSION["message"])) {
    $_SESSION["message"] = "";
}

if(!isset($_SESSION['num'])) {
    $_SESSION['num'] = rand(1, 100);
}   




    $new_game = "<a href='logout.php'><button class='btn'>Play again</button></a>";


if ($_POST['number']) {


    $number = $_POST['number'];

    if (is_numeric($_POST['number'])) { 



        if ($number > $_SESSION['num']) {
            $_SESSION['message'] = "<div class='bad-guess'>Too high!</div>";

        }elseif ($number < $_SESSION['num']) {
            $_SESSION['message'] = "<div class='bad-guess'>Too low!</div>";

        }else{
            $_SESSION['message'] = "<div class='lucky-guess'>Congratulations! ".$_POST['number']." was the number!</div><br>".$new_game;


        }   

    }else{
        $_SESSION['message'] = "<div> <b>'$number'</b> is not a number. Please insert a number!</div>";
    }

}

?>

问题是,然后我开始会话,我得到了错误,我的$ _SESSION ['message']索引是未定义的。然后我开始猜数字,我得到了正确的信息。那么如何为会话开始定义$ _SESSION ['message']?

2 个答案:

答案 0 :(得分:3)

index.php页面中的

把这个

echo $_SESSION['message'] != '' ? $_SESSION['message'] : 'No messages'; 

答案 1 :(得分:2)

检查index.php

中是否先设置了它
if(isset($_SESSION['message']))
{
    echo $_SESSION['message'];
}