Detect online users? - php

I'm not sure what would be the easiest way to do this. I need to be able to detect what users are online on my website. So when people are viewing a thread or something it will say next to the users name if they are ONLINE or OFFLINE. And at bottom of forum index it will say all the users who are online.
What would be the easiest approach to do something like this? I'm not sure if I will need a Javascript which would run every time a page loads or what.
Thanks :)

have a MySQL database with a user table
have a column in that user table which saves the "last seen"-time
update that column on every page request
when checking for online or offline, check if current time minus "last seen"-time is greater than some treshold you like
Edit: You could optionally make a javascript "ping" the server (request an empty page) every two minutes or so if you want people idling with your Website open to be displayed as online, too.

One approach is to store your users sessions in a database or another store like memchached (or ideally both What is the best way to handle sessions for a PHP site on multiple hosts?). Then you just look up the user in your store and see if their session is still active.
A solution like this: http://pureform.wordpress.com/2009/04/08/memcache-mysql-php-session-handler/

You need to hold some kind of a "session" table, where you hold the user and the time of when they visited a page.
If the time is older then 5 minutes the user is offline (and the row can be deleted).
The other users in the session table are "online".

First thing first, there's no way to accurately get the current online users count. The best you can do is get a rough number.
Think about this situation: a user logs in to your website, clicks some links, and just closes the browser tab without logging out. Actually this is quite common. Your server never knows that a user closes the browser, so the session of that user keeps alive for some time (30 minutes maybe) if the session stored on your server.
In some stateless web apps like Ruby on Rails apps, sessions are stored completely on the browser side (in the cookies), and the server totally forgets about the user after each request, and that makes counting online users nearly impossible. This is a tradeoff for simplicity and scalability.
So how can we get such a number? We must make assumption basing on compromise. We make such an assumption that a user is online if his/her last request was made less than 30 minutes ago, then we can get the number of "online" users by tracking the timestamp of the last request each user makes. Or we can assume that a user is online if his/her session on the server is still alive, and count the sessions on the server. Either way, we have to convince ourselves that the number of "dangling sessions" is negligible (I know it's hard).

Related

How can I make remember voting with cookies easier than this?

It is the most easiest to describe my problem with a working example: even if you are not logged in, YouTube remembers what you have watched, and next time gives you suggestions based on previous watched movies.
My site is similar in a way: the users can vote on articles without logging in, and the site remembers votes with cookies. I have figured out a working method, but there has to be an easier way - also now the DB usage is anything but optimized.
For every visitor there is a check if he has the cookies. If yes I query his votes. If not I create a dummy user, and send him out the cookies. Now I store this users "last_visit" timestamp. After this everything is the same for both users. My problem is that my DB is filling up with dummy users, so I made my cookies expire in 3 months and my site regularly check which users didn't visit my site in the last 3 months, and deletes them from the DB.
I know I overcomplicated this, but my vote system is using AJAX, and I couldn't find a method to send out a cookie (and create the dummy user) only if a vote happens and not every time a simple visitor browses my site - without vote.
Also a note: I insist on using cookies - I know it would be easier to store IP-s when a vote happens, but there are schools, businesses using the same IP, and I like to allow their users to use my site.
What did I miss here? How can this be optimized?
if they do not hold a permanent account, why store anything related to them in the database at all? just record their prior votes in the cookie. you would also store averall votes in the db, but anonymously, and not relate these to "users" at all.

Number of users logged in/out with session expire?

I'm running a php login script on my server. Whenever a user logs in the username is stored in $_SESSION['username'] and there exists a field in one of my DB tables called nonline used to store the number of users logged in.
When a user logs in, the value of nonline increases by one. And whenever a user logs out it decreases by one. Pretty neat so far. :P
The problem starts when, most of the users, like me, do not click logout, or visit the logout page as such. They log in, and just close their browser/tab when done. Doing so doesn't decrease the nonline value. So the value remains as such, even when the user is no more browsing my website.
Is there any way I can determine the number of users actually looking at my website at any given time so that its value changes even when a user closes his browser instead of clicking logout? I'm not using cookies for login.
Normally this will be done with a table which tracks last action, or last page load. The number n_online (you may want to add the _, noline starts with no, which is a little odd at first glance) will be the number who have made some form of action in the last n seconds - the number of people who actively logged out.
Unfortunately, there is not. Any solution that does what you want would involve the browser firing an HTTP request of some kind when the tab/window is closed, and this isn't going to happen.
The best you can do is have the users' sessions time out after a relatively short time (e.g. 15 minutes) and perform aggressive cleanup of expired sessions on every script that wants to know the actual number of active users. Be aware that this will be bad for performance.
If 15 minutes is still too long for you and you cannot decrease the session lifetime (because it would annoy your users if they were logged out after 10 seconds of inactivity), you can have your pages "ping" the server using AJAX to keep the session alive. This will allow you to have almost real-time results, but it will probably kill your performance, it will not work for users with JavaScript disabled, and is prone to malfunction if a user experiences transient connectivity problems.

How to detemine if someone is logged in and viewing your web page(s)

I have a private web app with login requirements.
I have seen many sites (mainly forum sites) that list the members that are currently logged in and viewing the site.
I think I can devise a way to look at session vars datetime stamps and make some assumptions, but I was wondering if there was a standard way out there, or a trick that is used, to capture and display that info.
Not looking for code here (per se), just looking for the logic used to do it.
Thanks.
The most common approach is to just update a timestamp every time the user does something, and count her as logged out after a defined inactivity time.
You can use a session variable so you don't have to update the timestamp in the database on every page load. In this variable, keep a timestamp of the last update, and when it's over five minutes ago, update the timestamp in db and session.
You can't know when someone is watching your site, but you can determine when a user last requested a page from your server. If a user has requested a page in (for example) the last five minutes, you could say he's still active and probably looking at a page of your site. As far as I know that's the most common way to determine the number of active users.
How much granularity are you looking for? Do you only want to show users who recently logged into the site, or do you want to display users who are viewing (or recently viewed) a particular forum post?
If the former, it depends on what your login and authentication framework currently looks like, but basically it would be a query of non-expired sessions.
If the latter, you would need to store what users viewed a particular page when. You could use a join table such as Users_Viewed_Pages with a timestamp. Then for a particular page, query the table by Page_ID and display the users who loaded that page recently.
I'd suggest a binary value in your database and toggle it when the user signs on. Then you can have a JS timeout to automatically sign the user out if they're idle for too long.
Implement your own session handler and store active sessions in the database. This also makes it easy to terminate a user's active session and/or keep a log of all sessions.

Check if user is offline

I have an online game. I wish to show how many user are online. The problem is to know when a user is offline.
Is there a way to perform a check on sessions cookie to acknowledge whether the session with the broswer was closed?
I was thinking about simply set a timeout on the server which launch a script that count how many session cookie are present, but how do I check if the session cookie is about somebody who's logged and not just a visitor?
How did you handle this?
1) I don't want to rely on a script fired with the logout button, since nobody ever logout... people simply close the browser.
2) About timestamps and registering activity? Since in my game users interact with an svg (not moving through pages), they generate a huge amount of clicks. Making a query for each click for each of them refreshing a record would be very expensive.
When the user interacts with the site, set their last activity time.
If it is longer than 30 mins or so, you can assume they are offline.
You can also explicitly set someone to offline when they click logout.
However, your case is a little different. You could use a heartbeat style script.
Whilst they are on the page, use setInterval() to extend the expiry date, up to a maximum range (in case the user leaves their browser window open for hours on end).
Since your code gets executed when the page is loaded you cannot make a check if the user closed his browser or not.
So the common approach would be to use timestamps and update this stamp if the user does something on your site and if the timestamp is older than say 5 minutes you just assume he is offline

How to implement a "who's online" feature in PHP?

How would one go about implementing a "who's online" feature using PHP? Of course, it would involve using timestamps, and, after looking at phpBB's session table, might involve storing latest visits in a database.
Is this an efficient method, or are there better ways of implementing this idea?
Edit: I made this community wiki accidentally, because I was still new to Stack Overflow at the time.
Using a database to keep track of everyone who's logged in is pretty much the only way to do this.
What I would do is, insert a row with the user info and a timestamp into the table or when someone logs in, and update the timestamp every time there is activity with that user. And I would assume that all users who have had activity in the past 5 minutes are currently online.
Depending on the way you implement (and if you implement) sessions, you could use the same storage media to get the number of active users. For example if you use the file-based session model, simply scan the directory which contains the session files and return the number of session files. If you are using database to store session data, return the number of rows in the session table. Of course this is supposing that you are happy with the timeout value your session has (ie. if your session has a timeout of 30 minutes, you will get a list of active users in the last 30 minutes).
There are many ways of implementing this.
You can implement this simply by polling.
Check clients by certain interval and count the numbers of clients replied back.
That value can be used as number of online users.
I think better way is using push technology instead of checking online people certain every x seconds or x minutes.
It simply let server know when people are entering and leaving by event.
So then server just increase and decrease the the online user counting variable when events come from clients.
I recommend Socket.IO, APE to look at.
Also there are many other to consider such as XMPP, Jabber.
I was thinking to do it this way:
When the user logs in, his userid and timestamp will be inserted in to a table.
Then for every 5 minutes, i will call a php script via ajax to check whether the user is logged in, and if so, update his timestamp in the table.
If the user is not logged in, just delete his record.
i think you can make it simply in php
create table user consist of , username , password and status(1,0)
in login system analyse username and password
then if username and password is match , run the query to select from table user , and fetch it
then get the status
Update user , set status into 1 , it means online
When you click logout , analyse session username and password , and select query from tbl user and got the status , and then set status into 0 it means offline

Categories