通过php会话变量检查特定用户是否在线 [英] Checking if specific user is online through php session variable

查看:45
本文介绍了通过php会话变量检查特定用户是否在线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试使用 php 会话变量在我的网页上显示所有在线用户.为此,每当用户登录或退出时,数据库中的一列都会设置为在线"或离线".但是这并不完全有效,因为当用户关闭浏览器时数据库不会更新(因此破坏了会话).那么有没有另一种方法来检查是否设置了某个 sessionid??

I'm currently trying to display all online users on my webpage using the php session variables. To do this, whenever a user logs in or out, a column in a database gets set to "online" or "offline".. However this doesn't entirely work since the database doesn't get updated when the user closes their browser (and therefor destroys the session). So is there another way of checking if a certain sessionid is set??

目前我正在这样设置会话:

Currently I am setting the session like this:

session_start();

$_SESSION['username']="Example Username";

要从当前用户页面检查是否有会话变量集,我们可以简单地使用:

To check from the current users page if there is a session variable set we can simply use:

if(isset($_SESSION['username']))
{
//username is set
}

但是如果我们需要检查特定用户是否在线,我们如何获取例如已设置的所有会话变量的数组?例如

But if we need to check if a specific user is online, how do we get for instance an array of all the session variables that have been set? e.g.

//Get all $_SESSION['username'] vars

//loop through array and check for specific $_SESSION

for($i=0; ... )
{
  if( $_SESSION['username'][$i] == "User 1" )
  {
  //do something
  }
}

从我目前阅读的所有内容来看,似乎没有办法在您的页面上获取所有会话的数组.那么有没有更好的方法呢,例如facebook、twitter 等如何处理这些东西?感谢您的帮助!

From all that I've read so far, there doesn't seem to be a way to get an array of all sessions on your page.. So is there a better way of doing it, e.g. how do facebook, twitter, etc handle this stuff? Thanks for your help!

推荐答案

除了记录用户上次访问您的任何网站资源的在线/离线标志之外,一个解决方案是在您的数据库中存储一个时间戳.然后,您可能会在 15 分钟或其他某个恒定值后将它们视为离线.

One solution is to store a timestamp in your database in addition to the online/offline flag that records the last time a user accessed any of your website resources. Then you might just consider them offline after 15 minutes or some other constant value.

另一种解决方案是在这里使用回调http://php.net/manual/en/function.session-set-save-handler.php 我认为您可以在其中处理 gc 回调并在您的数据库中设置离线标志.

The other solution is to play with the callbacks here http://php.net/manual/en/function.session-set-save-handler.php where I think you can handle the gc callback and set the offline flag in your database.

如果您在该页面上搜索 class SessionDB 或转到 此处 看起来有人已经在自定义类中实现了某些版本!

If you search on that page for class SessionDB or go here it looks like somebody has implemented some version of this already in a custom class!

这篇关于通过php会话变量检查特定用户是否在线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆