views:

827

answers:

3

I'm using session-based cookies with my website. To my complete surprise, I noticed if I set a session cookie (not a persistent cookie), close a tab, and then reconnect to the site, the session cookies are still there. That's not what I would have expected, actually. I would have expected the session cookies to be deleted.

If you close the browser, a session cookie is deleted, so why not closing a tab to have the same result?

Therefore, I'm using PHP5 and jQuery. Is there anything I can do such that when a tab is closed I can fix this session issue? Unfortunately the onbeforeunload event on the BODY tag is not useful here because when you click away from a page it fires that event, not just closing a tab.

+2  A: 

This is by design and trying to change it is a very bad idea. What if a user opens a link in a new tab and closes that? Should the session in the original tab be destroyed? Of course not! This demonstrates why you should not even think about this.

A session ends when the last browser window closes. If you want something else, you:

  1. do not want sessions;
  2. need to make your own "mini-session" infrastructure;
  3. are probably in for a world of hurt and bugs.
Sander
The problem here is a public environment, like a library, and someone's online profile with identity info inside. I need to come up with a solution.
Nevertheless, it seems like you have a few good answers to this question, and should pick one of them as the correct answer. Perhaps you want to also start a new question?
bignose
+1  A: 

My guess is that it depends on the actual browser. Chrome uses different processes per tab, so I doubt that session cookies will survive between different tabs.

Brian Rasmussen
This is actually an important thing to keep in mind. Thanks for pointing that out.
Please upvote answers you find useful.
Brian Rasmussen
+3  A: 

The session cookie is per-process not per window. So even if you selected New Window you'd still get the same session id. This behavior makes since. You wouldn't want a user to re-sign in each time they opened a new window while browsing your site.

I'm not aware off hand of any real way around this.

Paul Alexander
Paul, see my comment to Sander below that begins, "The problem here..."
In such circumstances, the tab closing isn't the main issue. It's controlling the expiration of the session more actively. You'll want to implement some sort of activity timeout on the client in JS that automatically logs out after no user activity. You'll find this type of behavior on most banking sites.
Paul Alexander
Paul, you are right. I slept on the issue and that's the course of action I plan to take. Now to put in another stackoverflow question on the most optimal way to implement that.
I think if someone figures out the cross-platform hack/kludge to detect with 90% accuracy that a tab has just been closed versus closing a page any other way, they will become a hero on the web.