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

时间:2013-01-05 15:51:46

标签: php

当我导航到一个被锁定的页面时(换句话说,当出现表示你必须Continue的框时),我收到了未定义的$_SESSION变量。在我加入{{1}之前}语句,我没有得到任何未定义的$ _SESSION变量但是现在需要if语句,我开始得到那些变量错误。

对于if (allowed_in()=== "Allowed"){未定义的错误,是因为我将$ _SESSION变量放在错误的位置?

下面是代码示例的$_SESSION示例:

QandATable.php

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

        }

        ?>

1 个答案:

答案 0 :(得分:1)

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

  

注意:

     

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

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