开发者

Sessions in PHP exists after Destroying

I am new to learning Php. I have created the following code.

<?php
/* 
 * Testing Sessions with PHP
 */
session_start();
$_SESSION['user_id'] = 'Testing User';
session_destroy();
?>

<html>
<head>
    <title> Sessions Page</title>
</head>
<body>
    <?php
       echo $_SESSION['user_id'];
    ?>
</body>
</html>

Now the 开发者_运维问答echo $_SESSION['user_id'] echos testing user. In my opinion it should not, as i have destroyed the session. what is the reason?


You need to unset the session vars. See http://php.net/manual/de/function.session-unset.php

Means, put session_unset() before you destroy the session.


The function session_destroy() will indeed destroy your session. The session is in this case the file (or db) on the server, holding your data. That means you cannot access this session on other pages afterwards.

The globale $_SESSION[] variable is a different story. It is filled from the session file, before the code on your page starts processing. Therefore it holds a copy of the data and stays in memory until your page has finished processing. You can clear this variable with session_unset(), but as well you can wait until the page has finished and all it's variables are destroyed anyway.


This appears to be (for whatever reason) by design. The correct way to do what you wish is.

session_start();
$_SESSION['user_id'] = 'Testing User';
session_unset();
session_destroy();

This code will remove all session variables from $_SESSION and then destroy the session.


Need to be more comprehensive as PHP sessions can really behave differently. The following works perfectly in all browsers to kill/destroy/unset all session info. Perfect to be used in sign-out file.

<?php
    session_start();
    session_unset();
    session_destroy();
    session_write_close();
    setcookie(session_name(),'',0,'/');
    session_regenerate_id(true);
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜