How to detect if a user has logged out, in php? How to detect if a user has logged out, in php? mysql mysql

How to detect if a user has logged out, in php?


2017 edit: These days, your best bet is using websockets to track presence on a page/site.


You cannot detect when a user closes their browser or navigates off your site with PHP, and the JavaScript techniques of doing so are so far from guaranteed as to be useless.

Instead, your best bet is most likely to store each user's last activity time.

  • Create a column in your user table along the lines of 'last_activity'.
  • Whenever a user loads a page, update their last_activity to the current time.
  • To get a list of who's online, just query the database for users with last_activity values more recent than 10/20/whatever minutes ago.


Store the timestamp of each acitivity of the user. When that time is more than 10 minutes ago, do the logout.

In PHP, you could do something like this:

session_start();if (!isset($_SESSION['LAST_ACTIVITY'])) {    // initiate value    $_SESSION['LAST_ACTIVITY'] = time();}if (time() - $_SESSION['LAST_ACTIVITY'] > 3600) {    // last activity is more than 10 minutes ago    session_destroy();} else {    // update last activity timestamp    $_SESSION['LAST_ACTIVITY'] = time();}

The same can be done on the database instead. There you could even get a list of users that are “currently” online.


You are wondering if you can detect if a user closed his browser. You kinda can with javascript but I would not rely on it (since javascript is easy to disable) But you can not with PHP, since PHP only runs when you are requesting a page. Not when the page is open.

To be safe you should track the user's last activity and if it's past a few minutes (5/10) then assume that user is gone. If he does something again though (after 6 minutes for example) then he's back online.