2

I currently maintain a DB table of users, when after logging in I update the table with their ID and login_time. This works to a point but currently I can't tell if the user has been active since the login or for how long.

Is there a better way to get a complete list of users that have been active in the past X minutes?

G-Nugget
  • 8,666
  • 1
  • 24
  • 31
Paul
  • 11,671
  • 32
  • 91
  • 143
  • 5
    You could add a "last seen" column in the table and refresh that every time the user makes a new request – Pekka Jan 14 '13 at 16:49
  • @Pekka That'll require another DB call so I wasn't sure that was the best solution. – Paul Jan 14 '13 at 16:50
  • @Pekka웃: What about if user is logged in but did not change the page? – Neeraj Jan 14 '13 at 16:52
  • 1
    Making a DB request should be okay for most sites. If you have *huge* traffic, you might want to switch to a memcache at some point, but a database call shouldn't cause any performance problems for a site with low to medium traffic. Any CMS-driven site without static caching makes dozens of them on every request – Pekka Jan 14 '13 at 16:53
  • 1
    @Paul, The end of a "visit" can only be defined by an explicit logout or a timeout. Take a look here: http://stackoverflow.com/questions/679657/find-number-of-open-sessions – Jonathan M Jan 14 '13 at 16:55
  • Cache it, write them back to the db at a suitable interval. The data is ephemeral, so if your entire system went nipples up and that didn't get written back, no big deal. – Tony Hopkinson Jan 14 '13 at 16:57
  • @Tony Any suggestions for a caching method? – Paul Jan 14 '13 at 17:01
  • @Paul, PHP isn't my thing Pekka mentioned memcache, but a quick google should get you a set of options, it's a pretty standard option – Tony Hopkinson Jan 14 '13 at 20:27

2 Answers2

3

The best way to get what you need would be a "Last Activity" column in the users table. You would just update it whenever a user access a page. Depending on what information you need it could replace the login_time column or it could be a new column.

G-Nugget
  • 8,666
  • 1
  • 24
  • 31
2

You'll have to keep track of when the user made their last request in your database as a separate table or column. You can then formulate a query to select, e.g. all users that have made a request in the last 5 minutes.

PHP itself does not store - or care for - that kind of information. Unless you happen to have your own session management module which does store this kind of information, then you could use data from that.

Magnus
  • 980
  • 4
  • 10