My website has a login script that checks user data from a mysql table. The table has several columns (name, username, pass, etc.), the most important (for the sake of this question) being the 'username' and 'online' columns. The 'online' column is a BOOL value (1 when online is true, 0 when false). When a user successfully logs in, $_SESSION variables are set to their data from the table, and I use the following to change the 'online' value from '0' to '1' in the table.
mysql_query("UPDATE Members SET Online='1' Where UserName='$username' AND Online='0'");
The script checks the value of 'online' so that if it is 1, they cannot log in, echoing a message stating that the user is already logged in.
Next, each page of the site has a 'log out' link that runs a script that unsets all $_SESSION variables and updates the online value from 1 back to 0.
mysql_query("UPDATE Members SET Online='0' Where UserName='$username' AND Online='1'");
This is where the problem comes in. If a user closes the browser window, the session ends automatically due to how php functions, which is fine because that's what I want to happen. However, I'd also like to update the table if the browser is closed. Otherwise, when a user closes their browser, they will not be able to log back in due to the fact that their online value is still 1. I know the using onunload or onbeforeunload won't work because that would run every time they refresh or change pages. I know I probably need to use some sort of session timeout, but every answer I've seen doesn't full explain how to go about doing that. I generally just see people post code without explaining how exactly it works or how it's supposed to be used. If anyone could help me with this, I would greatly appreciate it.
Thank in advance.
You should use AJAX to auto-refresh any script and if last activity > 5 minutes -> SQL query.