Possible Duplicate:
Destroy or unset session when user close the browser without clicking on logout
I am implementing a chat script for my client. The problem I am facing is, if the user logs out, I can program to end his chat status to offline, as the status is set to 1 when the user logs in, but I am confused about, what if the user close the browser without logging out. In this case the status in the db remains 1 as the user hasn't logged out.
Hope you understand the question. Please help.
Assuming you are using cookie-based sessions, set the timeout very aggressively.
http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-lifetime
You could also hook into the browser's unload event via JavaScript, and trigger a quick AJAX-request to your server that destroys the session.
http://eureka.ykyuen.info/2011/02/22/jquery-javascript-capture-the-browser-or-tab-closed-event/
I wouldn't rely on this client-side implementation, though - if the browser crashes, or the user force-closes it, that may not trigger the event. The browser itself may also limit how long it will give an onunload
event to complete, in consideration of the user. A combination of these two methods would probably be the most effective.
Set the user offline in the database when the session cookie expires or after a certain time of inactivity.
You can check this on every request.