How can I check in real time if a user is logged in? How can I check in real time if a user is logged in? ajax ajax

How can I check in real time if a user is logged in?


My solution is to use the jquery ready and beforeunload methods to trigger an ajax post request that will notify when the user arrives and leaves.This solution is "light" because it only logs twice per user.

support.html

<!DOCTYPE html><html><head><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><script>//log user that just arrived - Page loaded$(document).ready(function() {         $.ajax({        type: 'POST',        url: 'log.php',        async:false,        data: {userlog:"userid arrived"}    });});//log user that is about to leave - window/tab will be closed.$(window).bind('beforeunload', function(){    $.ajax({        type: 'POST',        url: 'log.php',        async:false,        data: {userlog:"userid left"}    });});</script></head><body><h2>Your support html code...</h2></body></html>

log.php

<?php//code this script in a way that you get notified in real time//in this case, I just log to a txt file$userLog = $_POST['userlog'];file_put_contents("userlog.txt", $userLog."\n", FILE_APPEND );//userid arrived//userid left

Notes:

1 - Tested on Chrome, FF and Opera. I don't have a mac so I couldn't test it on Safari but it should work too.
2 - I've tried the unload method but it wasn't as reliable as beforeunload.
3 - Setting async to false on the ajax request means that the statement you are calling has to complete before the next statement, this ensures that you'll get notified before the window/tab is closed.


@Gonzalon makes a good point but using a normal DB table or the filesystem for constantly updating user movement would be exhaustive to most hard disks. This would be a good reason for using shared memory functions in PHP.


You have to differentiate a bit between the original question "How do i check in real-time, if a user is logged in?" and "How can i make sure, if a user is still on the other side (in my chat)?".

For a "login system" i would suggest to work with PHP sessions.

For the "is user still there" question, i would suggest to update one field of the active session named LAST_ACTIVITY. It is necessary to write a timestamp with the last contact with the client into a store (database) and test whether that is older than X seconds.

I'm suggesting sessions, because you have not mentioned them in your question and it looks like you are creating the userID.txt file manually on each Ajax request, right? Thats not needed, unless working cookie and session-less is a development requirement.

Now, for the PHP sessions i would simply change the session handler (backend) to whatever scales for you and what makes requesting information easy.By default PHP uses the session temp folder to create session files,but you might change it, so that the underlying session handler becomes a mariadb database or memcache or rediska.

When the users sessions are stored into a database you can query them: "How many users are now logged in?", "Who is where?".

The answer for "How can I check in real time if a user is logged in?" is, when the user session is created and the user is successfully authenticated.


For real-time chat application there are a lot of technologies out there, from "php comet", "html5 eventsource" + "websockets" / "long polling" to "message queues", like RabbitMq/ActiveMq with publish/subscribe to specific channels.

If this is a simple or restricted environment, maybe a VPS, then you can still stick to your solution of intervalic Ajax requests. Each request might then update $_SESSION['LAST_ACTIVITY'] with a server-side timestamp. Referencing: https://stackoverflow.com/a/1270960/1163786

A modification to this idea would be to stop doing Ajax requests, when the mouse movement stops. If the user doesn't move the mouse on your page for say 10 minutes, you would stop updating the LAST_ACTIVITY timestamp. This would fix the problem of showing users who are idle as being online.

Another modification is to reduce the size of the "iam still here" REQUEST to the server by using small GET or HEADER requests. A short HEADER "ping" is often enough, instead of sending long messages or JSON via POST.

You might find a complete "How to create an Ajax Web Chat with PHP, jQuery" over here. They use a timeout of 15 seconds for the chat.