Destroying PHP Session

2019-03-01 00:46发布

问题:

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.

回答1:

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.



回答2:

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called.

In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that.

Example Destroying a session with $_SESSION

// Unset all of the session variables.
$_SESSION = array();

// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

// Finally, destroy the session.
session_destroy();
?>

Please see here for more details.



回答3:

<?php
session_start();
$s_id = session_id();
echo $s_id;


session_destroy();
session_unset();


session_start();
session_regenerate_id(true);
$s_id = session_id();

?>

Try this . It will work.