如何检查用户是否在线

时间:2016-09-30 17:03:15

标签: php

我正在尝试检查用户是否在我的网站上在线,例如用户登录到网站,php代码会将名为online的db行更新为'1',如果他退出到'0'。

但是如果用户刚刚退出该网站,该行将不会更新,我该如何检查该用户是否确实在线。

登录也创建了一个会话,其中包含以下内容:

$_SESSION['logged_in'] = true;

我怎么检查这个?

2 个答案:

答案 0 :(得分:5)

你不能这样做。您可以在每个网页浏览中更新last_activity列,并考虑在10-15分钟内没有网页浏览的用户处于非活动状态,但没有可靠的方法可以确切知道用​​户何时离开网站只是使用PHP

如果这是一个严格的要求(可能就像聊天应用程序一样),您需要使用websockets调查实时通信。

答案 1 :(得分:2)

您可以使用发布 - 订阅模式。让我们理解什么是发布 - 订阅模式。

publish–subscribe is a messaging pattern where senders of messages, called publishers, do not program the messages to be sent directly to specific receivers, called subscribers, but instead characterize published messages into classes without knowledge of which subscribers, if any, there may be. Similarly, subscribers express interest in one or more classes and only receive messages that are of interest, without knowledge of which publishers, if any, there are.

来源:Wikipedia

以下是使用RabbitMQ MQTT适配器的示例:

将用户A的应用程序订阅到主题“/ topic / user-a”,将用户B的应用程序订阅到主题“/ topic / user-b”,并将在线/离线状态发布到主题" / topic /存在&#34 ;.在后端服务器上创建一个程序以订阅" / topic / presence"。如果有任何更新来自用户A然后将更新发布给用户A的所有朋友。这样,用户B将收到用户A的在线/离线更新。

                User A             User B            PresenceListener

Subscribe       /topic/user-a      /topic/presence   /topic/presence

Publish         /topic/user-b      /topic/presence   friend list

这里的真正挑战是如何发布"离线"。一个案例是,如果用户在互联网仍处于活动状态时关闭应用程序,则应用程序可以发布"离线"服务器的状态,但当互联网停止工作时会发生什么?

让我们通过"遗嘱和遗嘱#34; (LWT)。

LWT消息并不关心检测客户端是否已脱机(该任务由keepAlive消息处理)。 LWT消息是关于客户端脱机后发生的事情。 可以利用LWT消息来定义代理客户端发布的消息,因为客户端处于脱机状态且无法再发布。

来源:http://tuanpm.net/what-is-mqtt/

对于具有在线离线状态的示例源代码,您可以查看Github https://github.com/Applozic/Applozic-Web-Plugin/中提供的Applozic Chat Javascript插件代码

演示页:https://www.applozic.com/docs/chat-examples/web.html