0

Here is some very simple code for sessions

ini_set('session.cookie_lifetime', 0);
session_start();
echo session_id();

var_dump($_SESSION);

$_SESSION["name"]  = "test";

I load the page once.

I then comment out

#$_SESSION["name"]  = "test";

I hit reload and can the $_SESSION variables.

If I completely close the browser and start it up, I expect the $_SESSION variable to be completely empty.

Instead I see that "name" is still part of the $_SESSION variable.

Please alter this code so that it empties the $_SESSION if I close the browser. When I open it again, the $_SESSION variable should be empty.

Padraig
  • 3,197
  • 4
  • 18
  • 26
  • what you could do is use session_unset(); and session_destroy(); on the first landing page of your site (ie. index.php) this would destroy any previous session then you could immediately follow that code with a session_start(); to start a new session...ONLY problem with this, every time they refresh the index.php, the session variables are reset. – iam-decoder Nov 12 '13 at 20:33
  • See this post for a way to expire session data after XX minutes: http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes there is no reliable way to do what you want (on browser close) unless you want to waste valuable resources polling the server every few seconds – Patrick Moore Nov 12 '13 at 20:37

1 Answers1

0

Not possible. PHP tracks sessions based on a cookie set in the browser, so if your browser persists cookies across separate launches, then your PHP session will continue as well. You could set your session expiry lower, but that applies to all sessions.

PHP has absolutely no concept of whether or not your browser has been closed between two requests.

Sammitch
  • 30,782
  • 7
  • 50
  • 77
  • But isn't it true that if we don't add an expiry date in the cookie then it expires when the browser closes? So the question is - is there a way to remove the cookie expiry date in the session cookie? That's what I kind of had in mind. – Padraig Nov 12 '13 at 21:37
  • This is what PHP says about session cookies : 'session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. The value 0 means "until the browser is closed." Defaults to 0.' Since I set that parameter why does the cookie not get deleted on browser close? – Padraig Nov 13 '13 at 20:42