Home » Php » php – destroy session when broswer tab closed

php – destroy session when broswer tab closed

Posted by: admin July 12, 2020 Leave a comment

Questions:

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();
How to&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.

Answer:

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.

Answer:

this link is very helpfull

But you need to add code to function endsession which is JavaScript function, you can use ajax to call your logout.php. it has worked for me:

$.ajax({
    url:"logout.php",
    method:'POST',
    contentType:false,
    processData:false,
    success:function(data)
    {
        alert("session destroyed");
    }
});