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.
Related
How could I write a code for recently viewed products? I use a database to create dynamic pages and thought I could store the ID number in a session or cookie and pull the image and title from the database. Although I dodn't know if this would work. I would only want it to display the last 5 items viewed and not show any duplicates. Any Ideas?
If the user is logged in, you can create a table called 'userViews' providing the userID and the viewed productID.
Then, you can select a query using 'SELECT DISTINCT' on the productID. This will select unique values. (Check http://www.w3schools.com/sql/sql_distinct.asp)
If the user is not logged in, I suggest you do the same but instead of using a userID, try to find something unique from the user. You could try setting a cookie or session with a random (unique) number and link that to the database.
The conventional way would be to store within a cookie. If you can encrypt the cookie, do so.
Remember, a cookie can be modified by the user. The #1 rule is to never trust user input. All in all, be sure to validate the information before displaying or you'll open yourself up to the world of attacks.
Store the IDs in an array? Seperate by ',' or '.' -- do NOT create 100 different cookies for storing IDs.
You COULD also use SQL to store the views... but why use un-needed sql queries? SQL is for storage, long term. Session and cookies are for current actions.
There are 3 ways you can show recently viewed products. (Maybe some other way but these 3 are mostly used).
Based On IP
Store recently viewed in Cookies
Session ID
Based on IP
This isn't a good idea, it's because there is chance two people are using same router and the person who did not see the product would see the other person recent view. (You may use IP based to show other people like in your area. etc..).
Based on Cookies
By using cookies you are 100% sure that your are display recent product to the person who is visiting your sites, but not all users/visitors have enabled the cookies also cookies can easily edit and a security risk if you did not encrypt properly.
Session ID
You can generate a random user_id for a visitors and store this information in database like this:
start_session();
if(!$_SESSION['user_id']){
$_SESSION['user_id'] = rand(1, 1000000);
mysql_query('INSERT INTO products_recent (user_id) VALUES ('.$_SESSION['userid'].')');
}
Also, you can select/update the user product views and display to that users.
And you can easily clean database every 24 hours if you want, or you can use this data for analysis purpose.
Finally - Registered Users
If register users view your product I high recommend save in database and show these recent view product every time he/she visit your store.
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.
Hello I have a website. created using php,mysql. I want to set a limit like.. only 10 user can login my website at same time. How can I do that kind of a setting? any body knows the solution kindly help me..
Use a database table to store the number of logged in users but you need to come up with some way of imposing a time limit on those users. I would suggest a field in the table which notes their last activity. When a new user attempts to login you need to apply some logic like this (pseudocode):
if(<10users){
login
} elseif(any of the users have no activity for 30 mins){
remove that user and login
} else {
inform user of no space
}
You would need to update the last activity every time a logged in user visits a new page.
Go read up on sessions in PHP, then write your own session handler - the first time as a learning exercise. Then write your own session handler again, fixing all the bugs from your first attempt and adding in the facility to count active sessions.
Note that the normal behaviour for session handlers is that the session data persists even after the session has timed out - its up to the garbage collector (and optionally the session loader) to clear up session data which is stale.
i would override php session handling and store user sessions in the database. you can find a simple tutorial here: http://www.raditha.com/php/session.php
this way you can simply check if there are more than 10 valid sessions stored in your database table. though you have to think about handling logouts and timeouts, as some standard timeout like 30 minutes might not work well in your application.
If you want 10 user logged on your site, disable the login box if there are more than 10 users logged in.
This presume that you have a table in the db that records the users that are logged in the site. The login procedure will write a new line in the table. The logout procedure will delete it.
Simply count the numbers of rows in this table to determine the number of users.
as answered above you have to maintain a table which will store the number of users who logged in,but whenever the user logs out then decrement that value....whenever a new user logins increment that value by checking it with ur limit
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.
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