I have a file base session mechanism in my PHP web application. I want to figure out if a user is online, idle, or logged out. Currently I have two solutions in mind but don’t know which one is better. Also I don’t know if there is an alternative which works better than these two. My main point is, I don’t want to store sessions in DB, so I want a solution that uses file base sessions.
Solution 1: I create session files based on user_id which is unique, then each time a user does something, I update the timestamp on the session, then that causes the session file to be updated/written on disk again. When I want to figure out if a user is online, I use his user_id to read the session file last timestamp, if it’s smaller than 5min, I assume he is online, if it’s more than 5min and less than 10min, I assume he is idle, anything beyond that I assume the user is out.
Solution 2: I do the same thing by having a last_login field in user table, each time user does something on the site, or views some pages, I update that field with the latest timestamp, now if I want to see that user is online, I just check his last_login timestamp to see if his time fits into either of that online, idle, or logout state which I explained in Solution 1
So my question is, which one is going to be faster and with less overhead. My web site has 5000 members, probably 700 to 1200 logged in members per day. I have a VPS but moving to a dedicated server soon. So any suggestion other than those two solution ? and which one you choose ?
Hmm. If you have a memory caching system installed, the best solution performance-wise might be to write a token for each user into the cache at the start of each request. You could set an expiry time of 10 minutes in your case, as you assume people are offline after that. The key you use to read and write the token could be something like ‘UA35’ with 35 representing the user ID. The value could be the timestamp of the last action.
I believe that some of the caches allow you to retrieve all cache entries with a specified prefix, so you could get all logged in / idle users from the prefix ‘UA’.
APC could be used to write and read the values for each individual user. I’m not sure whether there’s a good way to show all logged in users though. If it’s going to be used relatively rarely, you could iterate through all user ID’s and check for the cached value, but that sounds wrong.
For checking individual users, it would work very well. In your base controller’s beforeAction() method, you could do something like this:
I’m mainly suggesting a memory cache so you can avoid hitting the database an additional time for every single page request. This may or may not be necessary for you, depending on the load on your site’s database server. If your database can handle it, adding a last action field to the user table would allow you to easily query the logged in users and order them by the time at which they logged in.