刷新后无法访问PHP会话变量

刷新后无法访问PHP会话变量

问题描述:

I got a logical problem with this code:

<?php
if(isset($_POST['submit'])) {
    if($_POST['username'] != "" && $_POST['password'] != "") {
        $_SESSION["user"] = new User();
        $_SESSION["user"]->login($_POST['username'], $_POST['password']);
    }
}
?>

But after refreshing the page , the session is empty. Does somone know why the session could be empty? The login function is working correctly (tested it with fixed login data at every reload of the page).

Thanks in advance!

If you are storing an object in the session, you need to make sure that the class is defined (or available in an autoloader) before session_start() is called, otherwise PHP won't be able to deserialise the object.

See http://php.net/manual/en/oop4.serialization.php for more info.

Probably You have forgotten to start session, add

session_start();

before using any Session Variables.

You MUST use session_start(); at the very first in every file, where you want to access the $_SESSION variable. Else it won't work because PHP won't initialize the session itself.

You should write it like this:

<?php
session_start();

//your code ;)

?>

Hope it helps ;)