Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP best practice keep track of logged in users

Tags:

php

session

I want to show users who else is logged in as part of a comment system. What are best practices for keeping track of users? For example:

Do you keep track of all sessions and then mark them as closed. Or do you delete users upon logout, keeping track only of active users.

I'm thinking I should create a table with userid, time logged in, time logged out and/or status. Is that the way to go or is there some alternative approach of tracking session ids. If using a table, is there value in keeping sessionid. Should I delete row when session no longer active, negating need for whenloggedout field.

There is a login so easy to keep track of users logging in. However, it is harder to track users logging out since their session may be broken by browser crashing etc.

Is it best practice to consider users logged in as long as they have not destroyed session... for example, FB and Gmail will leave you logged in almost indefinitely--or should there be a time limit since last activity? The idea of saving to this table every time there is activity on site is not appealing.

Right now, I'm thinking of following:

create table loggedin (userid (int), whenloggedin (datetime), whenlogged out (datetime), loggedin(tinyint))

with the latter going to 0 either if whenloggedout not null or after some long time limit like 24 hours. I imagine FB while leaving you logged in for long periods of time, also keeps track of activity for purposes of chat etc. but not sure. I'm also thinking of letting the table expand, rather than deleting closed sessions but maybe that's a mistake.

Would this approach be considered adequate or is there a better way. Many thx for advice on this.

like image 219
user1260310 Avatar asked Apr 20 '12 10:04

user1260310


1 Answers

Constant Polling and using heartbeat are a good idea, but for some scenarios they may create useless load on server. I think you should think about the importance of keeping track of your users and use it very appropriately, especially considering the impacts your changes may have on load time.

like image 143
Haris Avatar answered Nov 15 '22 16:11

Haris