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

show_lol picture show_lol · May 20, 2009 · Viewed 12.5k times · Source

After the user successfully logs in, I store login = true in database. But how do I check if the user logged out by closing the browser without clicking the logout button? And also, how do I redirect user who has been inactive for 10 minutes to login page?

I am using php and mysql. Any help would be appreciated.

EDIT: Sorry if my question is not clear. I did use session to store whether they are logged-in or not. But, now I want to store the info in database, so that I can display their status on other pages. Let's say user1 has 3 friends. When displaying all his friends, user1 want to know whether his friends are online or offline. This is what I want. Any advise?

Answer

ceejayoz picture ceejayoz · May 20, 2009

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.