Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to completely destroy a session - even if the browser is not closed

Tags:

php

Is it enough to

session_start();   //  Must start a session before destroying it  if (isset($_SESSION)) {     unset($_SESSION);     session_unset();     session_destroy(); } 

when the user selects Log out from a menu, but does not quit his browser? I want to totally remove all existence of the session and $_SESSION

like image 304
Mawg says reinstate Monica Avatar asked Oct 16 '10 08:10

Mawg says reinstate Monica


People also ask

How do I destroy a browser session?

For a session, there are usually three ways it gets destroyed on the server side - a logout (which the app destroys the session), a period of inactivity (could be 15 minutes or whatever), or a "hard" timeout, you may want your users to always re-login every 8 hours for instance.

Is session destroy when browser is closed?

Browsers deletes the session cookies when the browser is closed, if you close it normally and not only kills the process, so the session is permanently lost on the client side when the browser is closed.

Which method is used to destroy the session?

A PHP session can be destroyed by session_destroy() function.

How do I start and destroy a session?

session_start() will start session. session_destroy() will destroy session. For setting session data you could do this.


1 Answers

According to the manual, there's more to do:

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.

The manual link has a full working example on how to do that. Stolen from there:

<?php // Initialize the session. // If you are using session_name("something"), don't forget it now! session_start();  // 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(); ?> 
like image 180
Pekka Avatar answered Sep 21 '22 04:09

Pekka