php点击其他网站后丢失$ _SESSION值

时间:2015-11-03 19:20:12

标签: php session

我有一个方法,其中我(两次)访问此值:

$_SESSION['loggedinUser'];

第一次它工作正常,但第二次失去了值。

 public function View($view, $model) {
    if (! isset($_POST['regist'])
            && ! isset($_POST['back'])
            && ! isset($_POST['login'])
            && ! isset($_GET['logout'])
            && ! isset($_GET['note_list'])
            && ! isset($_GET['file_list'])
            && ! isset($_GET['profile'])
            && ! isset($_GET['action'])) {       // LOGIN VIEW
        $view->login();
    }

    if (isset($_POST['regist'])) {               // REGIST
        $view->regist();
    }

    if (isset($_POST['back'])){                  // BACK
        $view->login();
    }

    if (isset($_POST['login'])) {                //LOGIN AND LOGGED IN VIEW
        $username = $_POST['user_name'];
        $pw = $_POST['pw'];

        if ($model->checLoginstatus($username, $pw) == true) {
            $id = $_SESSION['loggedInUser'];    // session is working fine
            session_start();
            $fname = $model->getNameToSession("user", "id", $id, 'firstname');
            $lname = $model->getNameToSession("user", "id", $id, 'lastname');
            echo "" . var_dump($id);
            $view->LoggedIn($fname . " " . $lname, null);
        }
    }

    switch ($_GET['action']) {
        case 'note_list':
            session_start();
            $id = $_SESSION['loggedInUser'];  // session gives back NULL

            $title = $model->getNameToSession("note", "user_id", $id, 'title');
            echo "" . var_dump($_SESSION['loggedInUser']);
            echo "" . var_dump($title);
            echo "<a href='#'>" . $title . "</a>";
            break;
        case 'logout':
            session_start();
            session_unset();
            session_destroy();
            header("Location:/");
            break;
    }
}

我错误地认为价值丢失了?

1 个答案:

答案 0 :(得分:0)

您应该在文档顶部加载session_start()

<?php
session_start();

// rest of your code goes here

?>

如果没有session_start()您在设置之前设置的$_SESSION个变量,请将其转移到此页面。