2

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

对于$_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

        }

        ?>

以下是完整的steps.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;
}

?>
4

1 回答 1

1

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

笔记:

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

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

于 2013-01-07T23:47:06.667 回答