How to implement a "who's online" feature in PHP? - 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

Related

Joomla 1.5 : How to find number of concurrent / active users in my joomla based intranet system

I have a Joomla 1.5.10 based Intranet system. Sometimes we see that number of DB threads are too high and performance become down. When I checked through Administrator section, I can see the number of logged-in users only. These number is between 1000-5000 only. is it correct to execute below query to find the concurrent active users:
select count(*) from jos_session;
For example, If I execute above query and check the logged-in user through administrator, below is the data:
select count(*) from jos_session; = 2628
logged-in users visible from admin section = 1545
Both results are not matching each other. Also, what is the best way to find the concurrent / active users in my system at a time?
I think just by analizing __session you won't get the info you need / want. If you need to understand what you see in back-end, check the module located at:
administrator\modules\mod_status\mod_status.php
There are all the queries listed. Important is to understand that guest is an user which is not authenticated, and also client_id (front-end (0) VS backend authentication (1)).
Here is the thing:
jos_session stores all the sessions that have not expired
probably you have a SSO authentication mechanism, which means that the user probably get a new session id if it closes and opens again the browser. Having more active sessions than users it's a clear sign that the session expiration time is set to high.
Just do a query against the jos_session:
SELECT `username`, count(username) FROM `jos_session` WHERE 1 GROUP BY `username`
If too many users have a too large value for count, reduce the session lifetime.
This way you will get a more realistic figure on how many users are at a certain time in the system, but again this is just a session, it does not provide you with exact information on how many users are actually performing an action on a website.
To put it in plain English is like saying: I know that 1500 users opened the Intranet in the last [FILL IN SESSION LIFETIME] minutes.
You need to understand how exactly do the DB threads get generated and why the value is high.
Basically, quoting the documentation, The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling mysql_close().
Might be worth checking if you have something like a JavaScript polling your server with AJAX requests to get some info, which might run even if the user just has the browser open.
Hope this helps in a way or another.

Design Question: how to show number of users online?

Planning to develop a LAMP web application. What general strategies can I use to display the number of users currently logged in to my site? I want to be able to accurately display something like, "There are currently 1000 users online" or "User John Doe is currently online".
A database will be involved. So every time someone logs into the site, you can have a field in a user's table for last_login. And then there can be a script that does a query against this user's table to count the number of rows last_login within the last x amount of time. It may be good to cache this and repopulate this cache every z amount of time, and then pull from this cache as oppose to running a query against the user's table every request. So database + some kind of caching system.
I recommend using the CodeIgniter PHP framework.
This will allow you to store your session data in the database very easily (you just enable it in the config.php file). Then you can query the number of session ids in the session table of your database.
Here is the information for the CodeIgniter session class so you can see how to use it:
CodeIgniter Session Class
Here is also a link to the CodeIgniter forums going through more detail of how exactly to get this implemented: CodeIgniter Forum
This is quite easy to do, but cannot be accurate. Html being stateless, there is no way of knowing if a user is still looking at your page or has left.
If you want to log anonymous and logged in users, you coud use a tracking cookie with a short timeout, say five minutes and have this cookie link to a database of active sessions.
count the number of active sessions in your session db.
If you're using your database to store session information, you can easily query the session table and get how many unique sessions there are stored.
Have some sort of last accessed time record in the DB, and record that the person has been active. Then query the DB for those users who have been active in the last 5mins or so. Will give you a close approx.

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.

Detect online users?

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).

[PHP]How do I count users online and users logged in, what method?

I've made a log in script for my site, the session stuff basically look like this.
if($_SESSION['loggedin']=="Yes"){
//user online stuff
}
For all other users the session is set
$_SESSION['loggedin']=="No";
How can i display active session that are set to yes or no? should i work anything with mysql tables and use crontabs? or should i count files in tmp(session directory) on apache?
What are the best methods and how can I do it?
Crontab is not necessary here. You can store last activity date and time somewhere (mysql database?), and use simple select, which would show amount of users, who were active within some timeout.
This table can be used for server-side tracking of logged in users. Table may also contain some additional information, like IP address, X-Forwarded-For IP etc.
You can store the users in a database, along with their login information, and check that every time you want to authenticate a user. This is far safer than using just session variables to authenticate.
You can count the number of users that are logged in by setting a bit for the user's record when they log in and turning the bit off when they log out / session expires, and counting the number of these bits that are on to see how many people are logged in.
If you need to display the actual users currently logged in, you're better off using a column in your users mysql table to track the current login state, and doing a periodical request via a cronjob, and store that info in a .txt file so that you can do the query just once for all logged in users and share the result by including it in your rendered html.
The other method (reading inside the session folder storage) is possible but more complex and probably less effective, although i haven't done any benchmarks. It just feels very hacky.

Categories