title: PHP/MySQL Update database on session timeout
body: <p>I'm working on a "flash website". In this program, I'd like to add an "Online Users" list, which relies on sessions: A session is started when a user logs in, and the user is marked as Online in the database. As soon as the logs out <strong>or</strong> closes the browser, the user is marked as Offline in the database. </p>
  
  <p>I know that running some functions when the browser is closed will require Javascript, and it's not safe either: If the browser were to crash, the functions wouldn't run. That's why I've settled for the database updating if the user logs out or if the user's <em>session</em> times out.</p>
  
  <p>I've been looking up session timeouts, and ran into this, along with many others like it marked as duplicates: <a href="https://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes">How do I expire a PHP session after 30 minutes?</a></p>
  
  <p>The problem with the answer's method is; It's a conditional sentence that checks if the user's last activity was X seconds ago, and if there was no activity, it times out. Useful in some websites, but useless for the Online Users list, since it updateds when a new request is sent, and since there won't be any requests after the user closes the browser.</p>
  
  <p>Also mentioned in other answers is the use of <code>session.gc_maxlifetime</code> and <code>session.cookie_lifetime</code>, but the Best answer states that using them is a bad idea; One doesn't destroy the session, just the cookies, and the other is "cost-intensive".</p>
  
  <p>What I want is the user to time out and the database to update and mark the user as Offline <strong>without</strong> using the If-Conditional sentence, or maybe with using a different If-conditional sentence that only has to be used once when the user logs in, like a timer or something, and whenever a request is sent, the timer restarts...those are just my ideas so far on how to solve this problem.</p>
  
  <p>But, how do I do this? I'm sorry if the answer is something very simple and obvious, I'm very new to PHP.</p>
  
  <p>Edit: <strong>Long Story Short:</strong></p>
  
  <p>I want to run a function after the user <em>closes his browser</em>, or is inactive for 20 minutes.</p>
  
  <p><strong>Clarification...</strong></p>
  
  <p>I want to update the database after 20 minutes of inactivity <strong>even if</strong> the browser has been closed.</p>