3

I must be really stupid because it seems a fairly obvious thing is completely confusing me right now.

I have a session...

ie $_SESSION['handbag_id'];

and at a certain point, I need to completely kill this session.

ie

// at the start of the page
session_start();

// elsewhere on the same page
unset($_SESSION);
session_destroy();

And yet, I can then go to another page, and do a

echo $_SESSION['handbag_id'];

And I've still got the same handbag_id as before.

What am I missing? Do I not understand how this works or do I have some server setting that reigns supreme over my desire to destroy its values?

willdanceforfun
  • 11,044
  • 31
  • 82
  • 122

3 Answers3

3

Don't do this

unset($_SESSION);

Do this

$_SESSION = array();

And finally

session_destroy();
Leigh
  • 12,859
  • 3
  • 39
  • 60
3

Session functions can be very tricky. To completely kill a session you need to assign a new value to the $_SESSION superglobal. Otherwise, all you do is unloading session data from current script. This should work:

session_start();
$_SESSION = array();
session_write_close(); // Not required

If you also need to open an entirely new session, you can do this:

session_regenerate_id(FALSE);
$tmp = session_id();
session_destroy();
session_id($tmp);
unset($tmp);
session_start();

Update:

A related question you may find useful: Close session and start a new one

Community
  • 1
  • 1
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
  • Looks a bit mad, I'm pretty sure you can just do this: `session_destroy(); session_start(); session_regenerate_id();` – Leigh Feb 07 '11 at 12:39
  • 1
    @Leigh - It looks mad until you do some testing. Seriously. Your code will probably leave the old session standing, ready to be recovered if you know the old ID. – Álvaro González Feb 07 '11 at 13:06
  • Thanks for this. I tried it, but that session_destroy() throws up an error that there is no session initialised to destroy. – willdanceforfun Feb 08 '11 at 00:43
  • @KeenLearner - And, is there a session initialised? – Álvaro González Feb 08 '11 at 08:03
  • No, it just throws up an error. So I guess problem solved! :) But now I have errors on screen. – willdanceforfun Feb 08 '11 at 23:04
  • I did. It said there is no session initialised. So a victory there. But my server is printing out the errors to the screen, then it attempts to session_start, but headers are already sent so this throws up more screen errors. I think if I supress the errors I would achieve the desired result. – willdanceforfun Feb 08 '11 at 23:37
0

use session_comitt before printing and see the magic :)

Rostyslav Dzinko
  • 39,424
  • 5
  • 49
  • 62
Ankur
  • 111
  • 8