简体   繁体   English

PHP计数登录用户

[英]PHP Count Logged-In Users

I'm having trouble figuring out how I can count the number of logged-in users in my application. 我在弄清楚如何计算应用程序中已登录用户的数量时遇到了麻烦。

What I have: When a user logs in, they get a session (which is used when the user wants to visit a protected page) and the IsLoggedIn column for the user in the users table is set to 1 to indicate that the user is logged in. When the user logs out, the value is set back to 0. Counting the number of 1s in the users table makes it easy to return the number of users logged-in. 我所拥有的:用户登录时,他们获得一个会话(该会话在用户要访问受保护的页面时使用),并且用户表中该用户的IsLoggedIn列设置为1以指示该用户已登录当用户注销时,该值重新设置为0。对users表中的1进行计数可以很容易地返回已登录的用户数。 But... 但...

The Problem: If the user closes the browser without logging out, the value in the database stays 1, indicating that the user is still logged in even though their session has ended when they closed the browser. 问题:如果用户没有注销就关闭浏览器,则数据库中的值将保持为1,这表示即使关闭会话的浏览器会话结束,用户仍然可以登录。

Question: Could some one suggest a proper way of doing this? 问题:有人可以建议这样做的正确方法吗?

Rather than a IsLoggedIn column, you should add a LastTimeSeen column. 而不是IsLoggedIn列,您应该添加LastTimeSeen列。 Any time a person visits a page you update the column: 每当有人访问页面时,您都会更新该列:

UPDATE members SET LastTimeSeen = NOW() WHERE id = $the_user_id

Then to get how many people are on the site at any given moment you use the query: 然后使用以下查询来获取在给定时刻网站上有多少人:

SELECT COUNT(*) FROM members WHERE LastTimeSeen > DATE_SUB(NOW(), INTERVAL 5 MINUTE)

That shows how many people have viewed a page in the past 5 minutes, which is the best you're gonna get without a much more complicated solution. 这表明在过去5分钟内有多少人浏览过某个页面,这是没有更复杂的解决方案所能得到的最好的结果。

Just to offer another solution: 只是提供另一个解决方案:

if ($user->isLoggedIn()) {
  touch("/writable/path/loggedInUsers/" . $user->id);
}

If you don't need to query this data, a local file touch is far faster than a DB write. 如果您不需要查询此数据,则本地文件访问比数据库写入快得多。 To get logged in users, scan the directory for filemtimes under N seconds old. 要登录用户,请在目录中扫描N秒钟以内的filemtimes。

Because of the way our site is constructed, it was necessary to use the ajax approach. 由于我们网站的构建方式,因此有必要使用ajax方法。 I'm using jQuery so it's relatively painless. 我正在使用jQuery,因此相对而言比较轻松。

These lines went into the $(document).ready function. 这些行进入$(document).ready函数。

fnShowImOnline();
setInterval('fnShowImOnline', 120000);

This is the javascript function... 这是javascript函数...

function fnShowImOnline() {
    $.get('ajax/im_online.php');
}

And here is the PHP 这是PHP

<?php
    session_start();
    if ((isset($_SESSION['user']))&&($_SESSION['authorized']=='authorized')) {
        include('../includes/db.php');
        db_connect();
        mysql_query("UPDATE members SET last_checked_in = NOW() WHERE user_id = {$_SESSION['user']['user_id']}");
    }

?>

The count is straight PHP/mySQL. 计数是直接的PHP / mySQL。

//  Members online.
$online_sql = "SELECT COUNT(*) FROM members where last_checked_in > DATE_SUB(NOW(), INTERVAL 5 MINUTE)";
$online_RS = mysql_query($online_sql);
$online_row = mysql_fetch_row($online_RS);
$online = $online_row[0];

For those times I need to update the numbers dynamically, this bit of ajax does the trick. 在那些时候,我需要动态更新数字,而ajax可以解决问题。

$.ajax({
    url: 'ajax/members_online.php',
    dataType: 'json',
    success: function(response) {
        if (!isNaN(response.total)) {
            $('#OnlineTotal').html(response.total + " Total ");
            $('#OnlineOnline').html(response.online +  " Online Now");
        }
    }
})

using this for the PHP/mySQL 将其用于PHP / mySQL

//  Members online.
$online_sql = "SELECT COUNT(*) FROM members WHERE last_checked_in > DATE_SUB(NOW(), INTERVAL 5 MINUTE)";
$online_RS = mysql_query($online_sql);
$online_row = mysql_fetch_row($online_RS);
$online = $online_row[0];
//  Members total.
$total_sql = "SELECT COUNT(*) FROM members";
$total_RS = mysql_query($total_sql);
$total_row = mysql_fetch_row($total_RS);
$total = $total_row[0];
$response = json_encode(array('total'=>$total,'online'=>$online));
echo($response);

This is working well for us. 这对我们来说很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM