How to check if the user is online?

Asked

Viewed 5,293 times

10

I am developing a project in PHP and using Mysql as a database. I only have one question about how to chat: How to know which users are online at that exact moment?

  • 10

    1-I do not recommend making a chat using only [tag:mysql] and [tag:php], for experience it will become unstable and difficult to maintain. 2-if you really want to use [tag:php] recommend using [tag:sockets]. 3-My main recommendation is to use [tag:websockets] in [tag:javascript], besides having an easier maintenance there are more libraries that do what you need

4 answers

13


You can use a set of techniques to get this information.

On the client’s side:

  • Listen to the closing event of the browser window, and when the user closes, send a signal to the server, indicating that the user has a less open window, and on the server will have to count how many pages the user has opened

  • Listen to mouse movement event, and if you stay for a while without moving the mouse, then the user is considered offline

To implement the chat:

  • the option that will give you the widest range in terms of browsers, is called long-time, but it is also the one that will give more work. See more about the technique: http://rberaldo.com.br/server-push-long-polling-php-ios/

  • another option that will be easier, is to use websocket, and create a server connection, which will be able to send messages when some chat event occurs... like send a message

4

The question has already been marked as answered, but as a reference for those who stop here in the future: use websockets, they have been around for some time and are the most suitable solution for real-time communication between browsers and Servers (a chat for example). Their basic idea is to keep a constantly open connection between clients and the server to allow real-time communication, you could emulate this using ajax and long-time, however the difference in performance is relevant (worse in this case) and long-Polling is an alternative solution that is usually preferred only in the absence of better mechanisms.

One of the only problems with the use of websockets would be the lack of support in browsers, a virtually irrelevant problem since now almost all major already has support and most (if not all) websockets libraries provide automatic fallback to long-Polling if necessary.

In case the problem of verifying who is online would be simple, see an example using socket.:

// código do servidor realtime
var onlineClients = {};
io.on('connection', function (socket) {
    onlineClients[socket.id] = socket;

    // on disconnected, unregister
    socket.on('disconnect', function() {
        delete onlineClients[socket.id];
    });

    // usado em um exemplo mais abaixo
    socket.on('enviarMensagem', function(mensagem) {
        io.emit('novaMensagem', mensagem);
    });
});

// código do cliente (browser)
<script>
  var socket = io();

  // usado em um exemplo mais abaixo
  socket.on('novaMensagem', function(mensagem) {
      alert(mensagem);
  });
</script>

When a client connects or disconnects your server is instantly aware and you can take action based on this. Let’s say for example that you want from PHP to send a "hello" to everyone who is on:

// código do servidor php, usando a elephant.io lib
$elephant = new Client($socketServerUrl);
$elephant->initialize();
$elephant->emit('enviarMensagem', 'ola');

Your php server would send a 'send' event to your Realtime nodejs server, which in turn would send the 'newMensage' event to all connected clients, when arriving at them would be fired a alert(mensagem); with the message sent (see code snippet with the comment "used in an example below").

1

Give preference to using websocket, but if you have a shared host other than this support follow something that can help.

if if you create a field(EX: time) and in each text message it updates this field with php team value ( EX: $tempo=time() ) in the area where you will get the result use the following select

$query = "SELECT * FROM users WHERE tempo > UNIX_TIMESTAMP() - 300";

in the case UNIX_TIMESTAMP() - 300 means 5 minutes plus vc can change to the time you want in seconds EX: UNIX_TIMESTAMP() - 60 = 1 minute

  • Your code and logic seem great, but that doesn’t work well here sorry I seem to be criticizing, but the point is websocket, Miguel’s answer explains well how long-Polling works and makes use mysql for server redundancy and even waste, so understand that in websocket the situation will be different from normal pages. Please understand only as a constructive criticism, see more ;)

  • I fully agree , I am passing more information if the user uses a shared host that does not offer this resource, I went wrong because I should have specified and I will do it. NOTE: I wish all members had their kind of approach, congratulations are members so the stack needs

  • It was not I who denied, but probably the person shares my opinion, it is not preferred or not about websocket, it is just about websocket, but since it was not the author who put the websocket tag then I will consider his response as an alternative to these limited server cases (such as shareds) ;)

  • so I specified in the update, as for regulations of the site I do not much leash because rules exist to be changed, I am even creating a post related to this because I see a separation of the staff here in many issues . Question

  • 2

    There are no "rules", there is model, who defines the rule is the community and just because you disagree with the model or rules does not mean that it allows you to do the opposite, the rules were formed by "people" that with more experience than both of us and for good reasons that only they know why they exist, it is up to us to follow them and debate maybe change them, but not "disobey"... Of course you do not need to follow the rule to the letter, but if you are very contrary you will more harm than help...

  • ... But about your answer is not bad only that it would be better put here: https://answall.com/questions/45125/usuarios-onlines-e-tempo-passado-no-site ... in this question your answer is perfect ;)

Show 1 more comment

0

The ideal would be to use Node.js (with the chat inside an iframe, connecting to Node.js which would be a separate PHP server), and Sockets.io as basic technology. There are even several example chats written in socket.io that could be used as a basis (example: http://socket.io/demos/chat/)

  • 3

    "The ideal" I think is a bit of an exaggeration, Node.js is just one of many possibilities. As an example, I wouldn’t trade my Websocket server which is super lean for Node.js, for example. As one of these alternatives, Node.js could possibly serve. Other than that, I think I missed answering what was asked (after all, the question is not "how do I chat", but how to detect if the user is online). I think I can improve the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.