Session Variables do not get destroy even using se

2019-03-06 11:05发布

问题:

session_start();
$_SESSION['user'] = "789456";
$_SESSION['name'] = "dummy";
$_SESSION['id'] = "123";
print_r($_SESSION);
session_destroy();
echo "Session End";
print_r($_SESSION);

My output is:

Array ( [user] => 789456 [name] => dummy [id] => 123)
Session End :Array ( [user] => 789456 [name] => dummy [id] => 123) 

Shouldn't the output just be:

Array ( [user] => 789456 [name] => dummy [id] => 123)

If I use session_unset() before session_destroy() then I get the result I expect. Is it always necessary to use session_unset() before session_destroy()?

回答1:

From the documentation:

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called.

In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that.

The easiest way would be: $_SESSION = array(); after calling session_destroy();.



回答2:

http://php.net/session_destroy

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called.

In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that.

session_destroy wipes the data from the underlying storage, but it leaves $_SESSION alone. When you refresh the page, it will be empty.

What you can do, however, is just do $_SESSION = array(); session_destroy(); (Though really that's almost redundant since session_destroy wipes the underlying data, but keeps the same session id -- the two statements are basically the same thing)