2

What is the difference and most secure way to clear login sessions in PHP? Basically going to call this when a user clicks log out in my application.

I am seeing:

 session_destroy()
 session_unset()

Or simply doing:

unset($_SESSION['my_key_1']);
unset($_SESSION['my_key_2']);

What is the best way?

3
  • Why do you need that? Garbage collector does that for you.
    – zerkms
    Commented Nov 9, 2012 at 6:47
  • When a user clicks log out, I need to clear sessions completely.
    – Justin
    Commented Nov 9, 2012 at 6:47
  • Because otherwise they stay logged in.
    – Justin
    Commented Nov 9, 2012 at 6:48

3 Answers 3

12

session_destroy is deleting whole session.

session_unset delete ony a variables from session - session still exist. Only data are truncated.

So, If you want to make memory free session_destroy is best.

1

The best solution I know is to use session_regenerate_id(true);

This will drop the current session data and regenerate session id.

Assigning a new session id is a good idea because it will help to treat a user as a completely new one (in case if something in your code relies on session id).

1

The session_unset() function frees all session variables currently registered. Meaning, it will do this:

unset($_SESSION);
$_SESSION = array();

The session_destroy() function will invalidate the whole session! The session hasn't took place.

2
  • 1
    session_unset right before session_destroy makes no sense.
    – zerkms
    Commented Nov 9, 2012 at 6:53
  • 2
    nope, you copied the code from some stupid comment. Comments are not the part of manual and rarely a good place to learn
    – zerkms
    Commented Nov 9, 2012 at 6:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.