Search code examples
phpsuperglobals

Session superglobal array


I just noticed that session_destroy() does not seem to be working for me.

Testing PHP code looks like this:

session_start();
session_destroy();
$_SESSION['session'] = 'session started';
print_r($_SESSION);

But the display still shows

Array ( [session] => session started)

Surely this should throw an error as the SESSION variable now does not exist?


Solution

  • session_destroy destroys the saved session data - in most cases, that's the session file.

    However, it doesn't affect the session variable itself.

    Therefore, so long as you are in the same request, you can continue to use the $_SESSION superglobal with all its previous values. To completely destroy that, you should use:

    foreach(array_keys($_SESSION) as $k) unset($_SESSION[$k]);
    

    Or code to similar effect.

    That said, it doesn't matter much - the session will be destroyed, and usually you only do this on logout pages that will only be displayed briefly before sending the user back to the homepage.