2

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?

S. A. Malik
  • 3,465
  • 6
  • 37
  • 56

4 Answers4

2

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.

madc
  • 1,674
  • 2
  • 26
  • 41
  • Great! it worked but, what is the difference between session_unset() and session_destroy() ? – S. A. Malik Sep 10 '11 at 07:26
  • 1
    @back http://stackoverflow.com/questions/4303311/what-is-the-difference-between-session-unset-and-session-destroy-in-php – NullUserException Sep 10 '11 at 07:30
  • The question still remains there in my mind. When the session has been destroyed why do session variables exist. This does not connect to logic at least for me. Please elaborate if you can. – S. A. Malik Sep 10 '11 at 07:42
  • The vars are already initialized. If you reload the page, this vars are gone. With or without session_unset(). You need this to get rid of the vars without reloading the page. – madc Sep 10 '11 at 09:21
2

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.

martinstoeckli
  • 23,430
  • 6
  • 56
  • 87
1

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.

Toby Allen
  • 10,997
  • 11
  • 73
  • 124
0

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);
?>
Aquaholic
  • 863
  • 9
  • 25