Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

destroy session when broswer tab closed

I have users login/logout application: I want to destroy session, its working fine when I close the browser (( all tabs )) , IE , Firefox working. But I want to destroy the session when user close the single tab . I am using :

session_set_cookie_params(0);
session_start();
like image 349
beginner web developer Avatar asked Jun 09 '12 05:06

beginner web developer


2 Answers

Browsers only destroy session cookies when the entire browser process is exited. There is no reliable method to determine if/when a user has closed a tab. There is an onbeforeunload handler you can attach to, and hopefully manage to make an ajax call to the server to say the tab's closing, but it's not reliable.

And what if the user has two or more tables open on your site? If they close one tab, the other one would effectively be logged out, even though the user fully intended to keep on using your site.

like image 177
Marc B Avatar answered Nov 14 '22 04:11

Marc B


Solution is to implement a session timeout with own method. Use a simple time stamp that denotes the time of the last request and update it with every request:

You need to code something similar to this

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
    // request 30 minates ago
    session_destroy();
    session_unset();
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time

More about this you can found here which is similar to your question Destroy or unset session when user close the browser without clicking on logout.

It covers all you need.

like image 27
Sanjay Avatar answered Nov 14 '22 02:11

Sanjay