PHP会话不起作用?在多个页面上使用变量


PHP sessions wont work? using variables on multiple pages

我想要的是,我可以使用一个变量在多个页面上使用
唯一的问题是,它不起作用,因为我认为我做错了什么
在看了几个小时后,我想可能出了什么问题,我决定把它发布在这里,所以也许你可以帮助我。
我的代码:
login.php:

<?php
    if(empty($_SESSION['pass']))  { 
        echo "U bent niet ingelogt.";
        echo '<form action="index2.php" method="post">';
        echo 'Code <input type="text" name="code">';
        echo '<input type="submit">';
        echo '</form>';
    } else {
        redirect($url);
    }
    $url = "index2.php";
    function redirect($url)
    {
        if (headers_sent()) {
            die('<script type="text/javascript">window.location.href="' . $url . '";</script>');
        } else {
            header('Location: ' . $url);
            die();
        }    
    }
?>

Index2.php:

<?php 
    session_start();
    // error_reporting(0);
    $CODE = $_POST["code"];
    $_SESSION["pass"] = $CODE;
    if ($CODE == "testpassword") {
        echo "password correct";
        echo '<br /><a href="index.php">Index</a>';
    } else {
        echo "Password wrong";
        echo '<br /><a href="login.php">Login</a>';
        exit();
    }
?>

Index.php:

<?php 
    session_start();
    // error_reporting(0);
    $CODE = $_POST["code"];
    $_SESSION["pass"] = $CODE;
    if ($CODE == "testpassword") {
        echo "password correct";
    } else {
        echo "Password wrong";
        exit();
    }
?>

在每个使用$_SESSION[]变量的页面上都需要session_start()

第一个文件中缺少。

您在login.php中忘记了session_start();

session_start用于创建或恢复现有会话。如果不在脚本中调用它,则不能使用$_SESSION数组。