Forum Current Online users - php

I have my own forum script in PHP (Yii2 Actually) and I want to show online users.
It would be easy if users would be active up until they log out. But that is not the case. Most of the time user leave their machines logged in but they are not active. Here I could use time limit (renewing time with each request and deleting those which are past that time limit) but isn't that overkill?
Is there any popular/better way of monitoring online users in the forum?

One possible way is to intercept user interface events in javascript and send an ajax notification to the server that the user is still there. Of course, this should be buffered, so that you don't get flooded with requests when the user moves the mouse. Something along the lines of
$('body').on('keydown mousemove scroll', function() {
clearTimeout(notifyTimer);
notifyTimer = setTimeout(function() {
$.get('my-server.com/user-is-active');
}, 60 * 1000);
});
On the server side, update the last-active field in the users table with the current timestamp. When displaying online users, select those with last-active > now - 15 min.

Related

How to monitor users in forum page

Is there a way to monitor a users activities in a particular web page? What I want to do is to see if a particular user is currently active in a forum, and if not active, the user should be displayed as absent from forum
$sql = "SELECT * FROM forumlog WHERE user_id = ".$_SESSION['user_id'];
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result) == 0){
$sql = "INSERT INTO forumlog (course_id, user_id, log_time)
VALUES(
".$_GET['course_id'].",
".$_SESSION['user_id'].",
".time().")";
$result = mysql_query($sql) or die(mysql_error());
}
The above code is what I use to log the user into the forum, this is because the forum is just a page on my site, and until the user clicks on the forum link he would not be logged in, but then I don't how to go about logging out the user from the forum page or checking to see if the user is active in that forum
When user enters page you can put the time in database. Everytime he refreshes page you should update this time.
To check which users are active you must select from database users that "time" is less than 5 minutes.
To check what users are absent you need to check users than time is greater than 5 minutes.
5 minutes of course can be changed to value you want.
If you want to be more particular you can name actions on your website and put it to database in structure like:
id, user_id, datetime, action, params
and put records
1, NOW(), 4, "viewforum", "forum_id=4,post_id=6"
and then you can select activites in last 5 minutes and check by user_id who is online.
You can do it like this, have a last_seen column in your DB, probably users column
Now Log the login activity of the user, when user switch between forum pages, keep updating the last_seen column, now to detect whether the user is online or offline you need to subtract the last_seen time from current time
if(strtotime($current_time) - strtotime($last_seen) < 60) { //60 Seconds /1 minute
echo 'User Is Online';
} else {
echo 'User Is Offline';
}
/* This will mark users online if they
were active before a minute, certainly you can extend it to 2-3 minutes
i.e 120/180 sec */
The traditional way of doing this has already been explained (updating the "last_activity" field every time the user loads some content).
I'm going to point a totally different way of doing this: websockets.
As you know http works in a request-response way. Connection is created by the client, and closed after a response has been sent (well, not always, depending on keepalive). So your problem ("how can I know if the user is still there?") just can't be solved unless you accept this: "if the user is not requesting more content, consider he's not online anymore".
Well, websockets have an advantage here, as the connection is not closed until the client or the server decide it's time to disconnect. So you can open a connection when the user enters the forum, and leave it there until the client leaves the page or closes the browser and thus the connection is closed.
The bad news: you have to write a server that listens for those connections. For example using Node.js. It's not difficult, but you need root access to the server, and then write a few lines of code.
The traditional way is easier, it's just an sql query, but it's good to know about alternatives.
edit
Quick example
Install Node.js: http://nodejs.org/
Install socket.io (it's a node.js module): http://socket.io/
Write a simple server like this:
var socketsConnected = 0;
var io = require('socket.io').listen(8080);
io.sockets.on('connection', function (socket) {
socketsConnected++;
// send him some information
socket.emit('totalSocketsOnline', { counter: socketsConnected });
// let the others know that the counter has changed!
socket.broadcast.emit('totalSocketsOnline', { counter: socketsConnected });
// socket events
socket.on('disconnect', function () {
console.log("Socket disconnected");
socketsConnected--;
// again, notify all clients!
socket.broadcast.emit('totalSocketsOnline', { counter: socketsConnected });
});
});
4- Write a simple client like this:
<script src="http://yourdomain.com:8080/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://yourdomain.com:8080');
socket.on('connect', function (data) {
// connected, we are so happy...
});
socket.on('totalSocketsOnline', function (data) {
// wohohoo lets show how many sockets we have online now
alert("We have "+data['counter']+" sockets online now!");
});
</script>
I've just coded that, so it will probably contain errors and won't work, but it's a place to start.
If you could go through a little stress you could make an open connection to the server using polling, and return an array position of the mouse for a span of 30 seconds, if the position remains the same with previous 30 seconds then you would conclude the user is not currently active. and could make a script to log the user out..... well, am just saying....

PHP front end user queue

I'm building a site where the users can control a webcam to turn it left and right.
Every user gets one minute of action. There is going to be a queuing system on the site that will allow one by one the users to control the camera.
So my question is the following, does anyone have a suggestion on how to build this queuing system? Are there any tutorials or code I can use?
Thanks a lot!
Have a database table to track the queue for example:
queue (id, session_id, start_time, last_update)
When users hit your page, insert them into the queue table. Use a regular ajax call (perhaps 30 seconds) on the page to poll the server to see if the current users turn is up.
If the user is the first record in the table then it's his turn, so update the start_time to the current time and send your ajax response telling the browser to display the UI with the buttons for the camera movement.
When a button is pressed, verify on the server side that it is infact this users turn and his start_time was < 1min ago, before allowing the action. If his turn is over, delete him from the table so that the next user becomes the first record and gets his turn, then send a response to the browser so that it can hide the camera UI and give a message.
In addition to inserting into the queue on hitting the page, also check to see if the user that is controlling the camera has had his 1min, if so then delete his record (or could be done on the cronjob below).
Each time the ajax poll fires, update the users last_update with a timestamp. Use a cronjob or just on the server side calls to check if any of the records in he queue have a last_update that is older than a short time, e.g. 30 seconds., if any are found then delete them because these are users that are no longer on the page. This will also prevent attackers trying to fill up your queue.
On the same cronjob, check if the user who's turn it is has the start_time populated, if after 30 seconds he hasn't started, delete from the queue.
The ajax calls would make it nice and seamless, but they aren't essential, if the user has Javascript disabled you can still detect that and use a meta refresh of the whole page instead.

Generate a list of online users?

I'm not awesome enough to write a chat application, and I'm trying to get one to work, and I've recently downloaded one from here, it's pretty good so far, as I've tested it out on XAMPP, but I have a slight problem. I'm trying to generate a list of online users to give it a more practical application-like feel, but the problem with that, is I have no clue how to do it easily.
When users login to my site, a session named g_username is created, (the chat says 'username', but I'll fix that) and from what I see so far, the easiest method would be to store their username in a database called OnlineUsers and call that data via Ajax, but, the other problem, is that it's session based, and sometimes the users can just leave, without logging out, and I intended to run a script to logout the user from both the OnlineUsers table, and by deleting the session.
If they leave without logging out, they'd be online forever! I could potentially suffix a bit of code on every page, that toggled an ajax event on page close, the event being a script that kills their OnlineUsers table record, but then again, that would load the server with useless queries as users jump between pages, as far as I'm aware.
Creating my entire site in Ajax isn't really an option, as it's a load of different sites combined in to 1 'place' with a social 'layer' (if you will) from a social service.
Does anyone see a way to do this that would make sense, and be easy to integrate, and do with Apache, without command line access?
You could so something like storing a timestamp of the users last action in a database, comparing that timestamp when outputting online users and making sure that it was done at most 1 min ago.
Run on all/vital pages:
(Deciding if the last action is outdated, you could also check if it was done for one minute ago to reduce the database-load)
if($user['lastAction'] < time()) {
//update into database, last action is outdated
}
When calculating the amount of users online and is within the loop of each timestamp
//If the users last action was within a minute, the user is most likely online
if(($row['lastAction']- time()) > 60*60)
//count user as online
you could have a cron job [if you have cpanel] running on the server once every 60secs or so, that checks when a user last sent anything via the chat if they have not in the last lets say 5mins then remove their entry from the online users list.

Log what page the user is currently on

I have a chatroom on my website. I want to compile a list of online users in the chatroom.
What is the best way to do this?
Would it be to log the last page the user visited and if it was that page, they are in the chatroom?
What different techniques can be used to do this?
Thanks
If you're using Comet in your chat application, then you'll have a channel open to the server, which would be bound to the client side as an open HTTP request.
As long as that request is open, the user is in the room. If the request closes, then the user is no longer in the room.
I would use sessions javascript library to record each page the user has visited and then retrieve those values in your chat client via javascript.
include the library on each page.
in the sessvars object, make an array sessvars.visited = []; [if sessvars.visited is not already an array]
Now on each page do something like this sessvars.visited[] = location.href
On the chat client page, use javascript to iterate through sessvars.visited to obtain all the URLs. For example, To list out the URLs in HTML w/ Jquery do the following:
var urlList = '';
$.each(sessvars.visited, function(key, value){
urlList += value + '<br />';
})
Note: Sessvars is an alternative to Cookies that has a very large capacity (10mb in most browsers). However, session data is only available in an active window. Information is lost once the window is closed, and as far as I know cannot be queried from other windows. So if chat is open in a different window than they were browsing in, this will not work.
You should make a javascript request to the server every x seconds.
You already have to do this (for retrieving the ongoing chat conversation and the list of users participating).
On the server side you know what users are on because of this request. You just have to log these requests.
Yshout works by doing an AJAX request against yshout/yshout.php every 6 seconds. Add a bit of code to yshout.php to track how many unique users it's seen in the last 10 seconds, and you should be set.
Edit: you want the names of everyone active in the chatroom? I'd be tempted to add a database table for this - every time they hit yshout.php, add a name+timestamp entry and delete all entries more than 10 seconds old. Then query with GROUP BY name to get unique users.
Edit 2: The chat client already does an AJAX request on yshout.php every six seconds. All you have to do is add a snippet of PHP code inside the 'if (isset($_POST['reqFor']))' clause (the bit that responds to the AJAX requests).
Keep it brief! Remember, it's going to get hammered on something like 150 times per minute.

How to know when user closes browser? Chat application

I have a simple chat client set up that allows users to login with a username and stores the messages they write in an sql database. Every 3 seconds, the database simply prints of all the rows. So it's basically a chat client.
I'd like to keep a list of who's online. How can I do this? How can I sense when someone has closed the browser?
Right now I'm pulling the username as
$name = $_COOKIE["name"];
and if this value is empty, I know they left. But once they left, it's too late to know what their username was so I can't keep track of who exactly left.
Ideas? I'm fairly new to php, javascript, and html, so keep that in mind :)
It is hard to send a last request to the server when someone closes the window, since Browsers usually don't wait for JS execution to finish when the user wants the window closed (as is the case with onbeforeunload).
Whenever I am confronted with a situation like this, I tend to use onbeforeunload to send a final request (which happens fast and usually finishes before browser window is closed), but also implement a timeout feature. The timeout feature would work as follows:
Everytime the user sends something to the server, the server recognizes this as 'still there'. At the same time, the client sets a timer of, say, 45 seconds. If the user does not type anything for 45 seconds, the client sends a 'still alive' signal on its own to stay connected.
Now, the server should execute a removeInactive() routine every 60 seconds (allow 15 seconds slow-connection margin, hence the 45/60 seconds) which removes any users who haven't sent a 'still alive' signal in the last 60 seconds.
This system worked fine for me so far, you could try it out for yourself.
Assuming your using AJAX to pull in the chat messages every X seconds, update your table of users at the time with the current timestamp for that user. Then anyone who has a timestamp say older than 10 seconds, you will know they have left the page.
put online users in a table that will have a field named like 'lastSeen' update this field every few seconds with ajax call..
ajax call be made someting like this :
window.setInterval(function() {
$.ajax({
url: _URL_ENGINE + "/updateLastSeen/?userid=" + userID,
success: function(data) {
}
});
}, 2000); // 2000 means 2 seconds
now to query the list of online players u can query them like
select * from players WHERE lastSeen > DATE_SUB(NOW(), interval 40 SECOND)
hope this helps
Use the onbeforeunload event.
You could possibly attach to the onunload event in javascript. Have a look at http://help.dottoro.com/ljflhicd.php for full details.
Refer these links. Sure this is a light for ur darkness.
Link1:
http://www.daniweb.com/forums/thread252828.html
Link2:
http://phpeasystep.com/phptu/9.html

Categories