查找活动会话总数 [英] Finding total number of active sessions

查看:137
本文介绍了查找活动会话总数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是PHP的初学者,正在为我的网站编写一些代码.我想获取当时处于活动状态的会话总数.我知道这是一项艰巨的任务,但有可能.我该怎么办?

I'm a beginner to PHP and I'm writing some code to my site. I want to get the total number of sessions that is active at that instant. I knew this is some difficult task but possible. How can I do it?

我用Google搜索过,有人说可以通过计算temp目录中临时会话文件的总数来实现.但是,它在哪里?

I've googled and some people say that it is possible by counting the total number of temporary session files in the temp directory. But, where is it located?

为获得更多解释,请考虑Joomla后端示例,该示例显示了当前访问者和管理员的总数,如下所示:

For greater explanation consider the example of Joomla backend which shows the total number of current visitors and administrators as shown below:

推荐答案

所有允许您显示访问者数量的网站都使用数据库会话处理程序(可能是mysql db甚至memcached).

All websites that allow you to show the number of visitors use database sessions handlers (it could be mysql db or even memcached).

会话表结构:

CREATE TABLE `sessions` (
`id` INT NOT NULL ,
`session_id` VARCHAR( 32 ) NOT NULL ,
`user_id` INT NOT NULL ,
`last_seen` DATETIME NOT NULL
) ENGINE = InnoDB;

会话ID 可以是内置的php会话ID,也可以是您自己的唯一哈希.内置会话的运行速度不是很快,但是您无需监视生成会话ID,到期日期等的情况.

Session ID could be either built-in php session id or your own unique hash. Built-in session works not so fast, but you don't need to watch for generating session ids, expiry dates and other.

用户ID 将是当前登录的用户ID,如果他是来宾,则为NULL.

User ID would be the current logged in user id, or NULL if he's a guest.

每次用户刷新页面时,您都应该更新session表:

Every time user refreshes the page you should update your session table:

  • 如果数据库中已经存在会话,请更新last_seen
  • 为没有访问权限的每个新访问者添加新行
  • 如果用户登录或注销,请更改user_id值
  • 删除过期的会话

此时,您可以使用简单的sql查询获取所有访问者的计数:

At this point you can get all visitors count using simple sql query:

SELECT
    COUNT(`user_id`) AS users,
    (COUNT(*) - COUNT(`user_id`)) as guests
FROM
   `sessions`
WHERE
    `last_seen` >= DATE_SUB(NOW(), INTERVAL 15 MINUTE)

这篇关于查找活动会话总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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