We had build an online dating website with a online chat functionality/feature.
The client had a requirement to show an user offline once user clicks on either Logout button
or closes the tab or browser. The first part was easily achieved, however for the 2nd part I had to spend
around 2 hours to find out the solution.
Problem:
When the user forgot to log out and closes the browser directly, the
session stil exists because when the user opens the browser again and comes back to the site
user is still loged in. And client does not want that to happen.
I/Client want the session to be destroyed when the user closes the browser
immediately.
There were a couple of solutions which came across, however i tested and used the 2nd option
1)
<body onunload=”destroy()”>
<script lenguage=”javascript”>
function destroy()
{
window.open(’destroyCode.php’); <– this page would have the PHP Destroy session code..
}
</script>
PHP file (destroyCode.php):
session_destroy();
2) In your php.ini file, set the value:
session.cookie_lifetime=0
Or, before EVERY session_start() call, use:
session_set_cookie_params(0);
—
I had a conception that if you set a cookie (or session), the session automatically destroys on browser close. Howerver this did not happen as I had the session/cookie available in my temp folder.
While that can be true for cookies (depending on the settings), that is not true for sessions. Sessions are stored on the server, the server has no way of knowing when you close your browser. Sessions are destroyed after a certain amount of time of inactivity.
You cant destroy a session when the browser closes. It requires a server side command to do close a session. That mean, you could have javascript make an ajax call to a script when the browser closes.
Related posts:








