是导致未定义$_SESSION变量的代码结构


is structure of code causing undefined $_SESSION variables?

当我导航到一个被锁定的页面时(换句话说,当你必须要Continue的框出现时,我得到未定义的$_SESSION变量。在我包含if (allowed_in()=== "Allowed"){语句之前,我没有得到任何未定义的$_SESSION变量,但现在需要if语句,我开始得到这些变量错误。

对于$_SESSION未定义的错误,是因为我将$_SESSION变量放在错误的地方吗?

下面是QandATable.php顺序的代码示例:

        <?php
        ini_set('session.gc_maxlifetime',12*60*60);
        ini_set('session.gc_divisor', '1');
        ini_set('session.gc_probability', '1');
        ini_set('session.cookie_lifetime', '0');
        require_once 'init.php'; 
        //12 hours sessions
        session_start();
        include('steps.php'); //exteranlised steps.php
?>
        <head>
<?php
        if (isset($_POST['id'])) {
        $_SESSION['id'] = $_POST['id'];
        }

        if(isset($_POST['sessionNum'])){
                    //Declare my counter for the first time
                    $_SESSION['initial_count'] = $_POST['sessionNum'];
                    $_SESSION['sessionNum'] = intval($_POST['sessionNum']);
                    $_SESSION['sessionCount'] = 1;
            }
        elseif (isset($_POST['submitDetails']) && $_SESSION['sessionCount'] < $_SESSION['sessionNum']) {
            $_SESSION['sessionCount']++;
        }
?>
        </head>
        <body>
        <?php 
    //once session is expired, it should log the user out, but at mo this isn't happening
        if ((isset($username)) && (isset($userid))){ //checks if user is logged in
            if (allowed_in()=== "Allowed"){
        //QandATable.php code:
        }else{
        $page = allowed_in()+1;

        ?>
        <div class="boxed">
          <a href="<?php echo $steps[$page] ?>">Continue with Current Assessment</a>
        <?php   
        }
        }else{ 
        echo "Please Login to Access this Page | <a href='./teacherlogin.php'>Login</a>"; 
        //show above echo if user is not logged in
        }
        ?>
下面是完整的步骤。php:
<?php
$steps = array(1 =>'create_session.php',2 => 'QandATable.php',3 => 'individualmarks.php',4 => 'penalty.php',5 => 'penaltymarks',6 => 'complete.php');
function allowed_in($steps = array()){
// Track $latestStep in either a session variable
// $currentStep will be dependent upon the page you're on
if(isset($_SESSION['latestStep'])){
   $latestStep = $_SESSION['latestStep'];
}
else{
   $latestStep = 0;
}
$currentStep = basename(__FILE__); 
$currentIdx = array_search($currentStep, $steps);
$latestIdx = array_search($latestStep, $steps);
if ($currentIdx - $latestIdx == 1 )
    {
       $currentIdx = $_SESSION['latestStep'];
       return 'Allowed';
    }
    return $latestIdx;
}
?>

session_start()必须在任何内容之前。

注意:

要使用基于cookie的会话,必须先调用session_start()输出任何内容到浏览器。

http://php.net/manual/en/function.session-start.php