Search code examples
phpsecuritysessiondestroy

Destroying PHP Session


There are lots of pages on stackoverflow about destorying session. Trust me, I have been reading them all and I came across this: Why does my session remain?

My question is simple, is it really true that I need to do all of the below just to properly destroy a session?

$tmp = session_id();
session_destroy();
session_id($tmp);
unset($tmp);

This is the only page that suggests such extreme measures. Most pages just suggest session_destroy();.

Just to clarify because there seems to be some confusion I am looking for the most efficent method that is effective.

Thanks in advance.


Solution

  • New answers have stopped coming in so I am putting in what I learnt based on all of the answers. This is an aggregation of the various answers. Hopefully it will help others. The most efficient method that is 100% effective for destroying a session is listed below:

    if (ini_get("session.use_cookies")) 
    {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params["path"], $params["domain"],
            $params["secure"], $params["httponly"]
            );
    }
    
    $_SESSION = array();
    $tmp = session_id();
    session_id($tmp);
    unset($tmp);
    session_unset();
    session_destroy();
    session_write_close();
    session_regenerate_id(True); // true indicates the need to delete the old session
    

    Thanks to everyone for their help showing me how to do this. This was not a single person effort. I would particularly like to thank @Kerrek SB, @Uday @Dhruvisha. If you have more suggests please feel free to add comments and I will edit my answer.