PHP 正在检查用户是否在线

PHP Checking if user is online

我不完全理解 PHP 时间函数,但我的印象是我的函数应该有效:

function user_status($timestamp){
        $online = date('Y-m-d H:i:s', strtotime('-5 minutes', strtotime(date('Y-m-d H:i:s'))));
        $away = date('Y-m-d H:i:s', strtotime('-15 minutes', strtotime(date('Y-m-d H:i:s'))));
        $offline = date('Y-m-d H:i:s', strtotime('-30 minutes', strtotime(date('Y-m-d H:i:s'))));

        if(strtotime($timestamp) >= $online){
            return 'online';
        } else if(strtotime($timestamp) >= $away){
            return 'away';
        } else {
            return 'offline';
        }
    }

当我传递用户上次活动时间的时间戳时,它总是 returns 在线。这里有什么问题?我只是错误地格式化了状态变量时间吗?

我不得不承认 PHP 中的 date/time 功能有点繁琐。这就是我在处理日期和时间时总是使用 Carbon 工具箱的原因。如果您使用的是作曲家,那么只需在您的控制台中输入 composer require nesbot/carbon 即可简单地包含它。

它不仅非常完整且易于使用,而且还使您的代码更具可读性。您使用 Carbon 的代码看起来像这样:

function user_status($timestamp){
    $lastAction = Carbon::createFromTimeStamp($timestamp);
    $minutesIdle = $lastAction->diffInMinutes(Carbon::now());

    if ($minutesIdle > 30) {
         return 'offline';
    } else if ($minutesIdle > 15) {
         return 'away';
    } else {
         return 'online';
    }
}

我还没有测试代码,但我相信它应该可以解决问题。

话虽这么说,您的代码也不应该那么难以运行。

  • 删除日期解析,并坚持使用时间戳(如果您不知道,这基本上是自纪元以来的秒数)。
  • 从最大间隔开始,然后逐步降低,否则您确实总是会得到 'online' 作为答案 (30 > 15 > 5)。
  • 最后一个时间间隔 $offline 甚至都不需要,反正您也不会使用它。

代码看起来像这样:

function user_status($timestamp){
    $now = time();
    $online = $now - 5*60;
    $away = $now - 15*60;
    // just for readability, you could also do $online = time() - 300; and so on

    if($timestamp <= $away){
        return 'offline';
    } else if($timestamp <= $online){
        return 'away';
    } else {
        return 'online';
    }
}