Is this a proper way to destroy all session data in php?

Got it from php.net, but I am not sure is this how everybody destroy all sessions?

// Unset all Sessions
$_SESSION = array();

if (isset($_COOKIE[session_name()])) {
    setcookie(session_name(), '', time() -42000, '/');
}

    session_destroy();

Does the code will destroy all the sessions?? Is it the most common way? how do you guys destroy php sessions?

Oh yeah, btw, what is that session_name()? All session name? e.g $_SESSION['var1'], $_SESSION['var2'], ... ?

I dont need to use unset($_SESSION['var1']); any more right?

Whats the different between using session_destroy() and unset($_SESSION[])?


Solution 1:

You should first know what sessions are: You can consider sessions as a data container on the server side that’s associated with a random identifier, the session ID. That session ID needs to be provided by the client so that the server can load the data associated to that session ID (and thus to that session) into the $_SESSION variable. Everything in that $_SESSION variable is also called session variables of the current active session.

Now to your questions:

Does the code will destroy all the sessions?? Is it the most common way? how do you guys destroy php sessions??

The provided code just deletes the session data of the current session. The $_SESSION = array(); statement will simply reset the session variable $_SESSION so that a future access on the session variable $_SESSION will fail. But the session container itself is not deleted yet. That will be done by calling session_destroy.

See also Truly destroying a PHP Session?

Oh yeah, btw, what is that session_name()?? All session name? e.g $_SESSION['var1'], $_SESSION['var2']... ?

The session_name is just used to identify the session ID parameter passed in a cookie, the URL’s query or via a POST parameter. PHP’s default value is PHPSESSID. But you can change it to whatever you want to.

I dont need to use unset($_SESSION['var1']); any more right???

No. The initial $_SESSION = array(); deletes all the session data.

Whats the different between using session_destroy and unset($_SESSION[])??

session_destroy will delete the whole session container while unset or resetting the $_SESSION variable will only delete the session data for the current runtime.

Solution 2:

This only destroys the current users session, not all the other users session.

Try using the session_save_path() to find out where the session data is being stored, and then delete all the files there.