Skip to content Skip to sidebar Skip to footer

How Can I Destroy Sessions If User Closes The Browser Window Or Navigates Away From Page In Php?

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 ca

Solution 1:

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.

Solution 2:

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.

Solution 3:

The first set the $config['sess_expiration'] to 0

This however has the effect of creating a cookie which actually lasts 2 years due to code in the system/libraries/Session.php file

The next us to set the $config['sess_expiration'] to -1

This just didn’t work for me full stop. When I logged in it saved the session variable then when I went to the next page it had disappeared.

Solution 4:

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).

Solution 5:

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

Post a Comment for "How Can I Destroy Sessions If User Closes The Browser Window Or Navigates Away From Page In Php?"