views:

267

answers:

4

I have some sessions that are saved. I want to destroy all the sessions if the user closes the browser window or a single tab or navigates away from the page. Is there any way I can do this?

A: 

Well, I'm using CodeIgniter for all my project. CodeIgniter have session class that store the data using cookies. I can set the cookies timeout in the application config. Set it to 0 will make the cookies only last while the page open, and when all tabs of the page closed in the browser, the cookies will be automatically deleted.

If you don't want to use another framework, then you can use cookies to hold session data that will only last until user close the browser tab. Use setcookie to write the cookie data, and read it from $_COOKIE variable.

Donny Kurnia
Cookies don't hold session data
Col. Shrapnel
Wow, that's confusing! Do you know the difference between sessions and cookies?
animuson
Cookies hold the PHPSESSID, which is what links the user to his server-stored session data.
St. John Johnson
Donny Kurnia
A: 

Similar to Donny's answer, but instead of using Codeigniter, you can just tell the built in Session class to change the PHPSESSID cookie to expire on browser close:

session_set_cookie_params(0);

This has to be called after session_start() on every page you use it (otherwise it is reset to the default from the ini parameter session.cookie_lifetime).

St. John Johnson
I'd love to know why I got a downvote. If the PHPSESSID cookie expires, then the current user loses his session.
St. John Johnson
A: 

It's quite complicated nowadays with all the modern tabbed browsers. So, you can rely only on the session timeout. Not a big deal though. Are you sure you really need this? That would make pain in the bottom for the users.

Col. Shrapnel
A: 

You cant destroy a session when the browser closes!!! Session needs a server side instruction to be destroyed. You can set the session to be destroyed after some time of inactivity.

Study the http://www.php.net/manual/en

Dr Casper Black
Study the manual? What a generic suggestion, -1.
St. John Johnson
No it is not a generic suggestion, the answer is given, and a reference.
Dr Casper Black