search
HomeBackend DevelopmentPHP TutorialDetailed explanation of four methods to count the number of people online using PHP

This article brings you relevant knowledge about PHP. It mainly introduces how to count the number of people online. You can use table statistics, redis ordered set statistics, and hyperloglog. Do statistics and so on. Let’s take a look at it. I hope it will be helpful to everyone.

Detailed explanation of four methods to count the number of people online using PHP

Recommended study: "PHP Video Tutorial"

How many people visit a business system website every day, and how many people are online How many? We must reserve this kind of business during development, and it is also within our design scope! Because a running website uses statistics every day.

How to count the number of people online? There are several solutions. The code uses the laravel framework. Can be used as a reference during development.

1 Use table statistics method

Use a data table to count the number of people online. This method can only be used when the amount of concurrency is not large.

First we create a new table: user_login

Detailed explanation of four methods to count the number of people online using PHP

Edit

user_login table

Simulate user login, no user exists Just store it in the table, and update the login information if it exists

// 客户端唯一的识别码
$client_id = session()->getId();
//用户是否已存在
$user = DB::table('user_login')
    ->where('token', $client_id)
    ->first();
//不存在则插入数据
if (empty($user)) {
    $data = [
        'token' => $client_id,
        'username' => 'user_' . $client_id, // 模拟用户
        'uid' => mt_rand(10000000, 99999999),   //模拟用户id
        'create_time' => date('Y-m-d H:i:s'),
        'update_time' => date('Y-m-d H:i:s')
    ];
    DB::table('user_login')->insert($data);
} else {    
    // 存在则更新用户登录信息
    DB::table('user_login')
     ->where('token', $client_id)
     ->update([
          'update_time' => date('Y-m-d H:i:s')
      ]);
}

Here we also need to regularly clean up users who have no operations. If the user has no operations within an hour, we can record it as an invalid user

The code is as follows:

// 客户端唯一的识别码
$client_id = session()->getId();
//用户是否已存在
$user = DB::table('user_login')
    ->where('token', $client_id)
    ->first();
//不存在则插入数据
if (empty($user)) {
    $data = [
        'token' => $client_id,
        'username' => 'user_' . $client_id, // 模拟用户
        'uid' => mt_rand(10000000, 99999999),   //模拟用户id
        'create_time' => date('Y-m-d H:i:s'),
        'update_time' => date('Y-m-d H:i:s')
    ];
    DB::table('user_login')->insert($data);
} else {    
    // 存在则更新用户登录信息
    DB::table('user_login')
     ->where('token', $client_id)
     ->update([
          'update_time' => date('Y-m-d H:i:s')
      ]);
}

Functions we can implement:

1) Current number of people online

2) Number of people online within a certain time period

3) Latest Online users

4) Specify whether the user is online

// 可实现功能一:当前总共在线人数
$c = DB::table('user_login')->count();
echo &#39;当前在线人数:&#39; . $c . &#39;<br />&#39;;
// 可实现功能二:某时间段内在线人数
$begin_date = &#39;2020-08-13 09:00:00&#39;;
$end_date = &#39;2020-08-13 18:00:00&#39;;
$c = DB::table(&#39;user_login&#39;)
    ->where(&#39;create_time&#39;, &#39;>=&#39;, $begin_date)
    ->where(&#39;create_time&#39;, &#39;<=&#39;, $end_date)
    ->count();
echo $begin_date . &#39;-&#39; . $end_date . &#39;在线人数:&#39; . $c . &#39;<br />&#39;;
// 可实现功能三:最新上线的用户
$newest = DB::table(&#39;user_login&#39;)
    ->orderBy(&#39;create_time&#39;, &#39;DESC&#39;)
    ->limit(10)
    ->get();
echo &#39;最新上线的用户有:&#39;;
foreach ($newest as $value) {
    echo $value->username . &#39; &#39;;
}
echo &#39;<br />&#39;;
// 可实现功能四:指定用户是否在线
$username = &#39;user_1111&#39;;
$online = DB::table(&#39;user_login&#39;)
    ->where(&#39;username&#39;, $username)
    ->exists();
echo $username . ($online ? &#39;在线&#39; : &#39;不在线&#39;);

2 Use redis ordered collection to implement online population statistics

Because it is in memory, it is very efficient and can be counted Various aggregation operations can be performed on the number of people online within a certain period of time. But if there are a lot of people online, it will take up more memory. Another point:

Invalid users cannot be cleared through user operation time. Only users who log out manually will be deleted from the collection.

The code is as follows:

// 客户端唯一的识别码
$client_id = session()->getId();
echo $client_id . &#39;<br />&#39;;
// 按日期生成key
$day = date(&#39;Ymd&#39;);
$key = &#39;online:&#39; . $day;
// 是否在线
$is_online = Redis::zScore($key, $client_id);
if (empty($is_online)) {    // 不在线,加入当前客户端
    Redis::zAdd($key, time(), $client_id);
}
// 可实现功能一:当前总共在线人数
$c = Redis::zCard($key);
echo &#39;当前在线人数:&#39; . $c . &#39;<br />&#39;;
// 可实现功能二:某时间段内在线人数
$begin_date = &#39;2020-08-13 09:00:00&#39;;
$end_date = &#39;2020-08-13 18:00:00&#39;;
$c = Redis::zCount($key, strtotime($begin_date), strtotime($end_date));
echo $begin_date . &#39;-&#39; . $end_date . &#39;在线人数:&#39; . $c . &#39;<br />&#39;;
// 可实现功能三:最新上线的用户,时间从小到大排序
$newest = Redis::zRangeByScore($key, &#39;-inf&#39;, &#39;+inf&#39;, [&#39;limit&#39; => [0, 50]]);
echo &#39;最新上线的用户有:&#39;;
foreach ($newest as $value) {
    echo $value . &#39; &#39;;
}
echo &#39;<br />&#39;;
// 可实现功能四:指定用户是否在线
$username = $client_id;
$online = Redis::zScore($key, $client_id);;
echo $username . ($online ? &#39;在线&#39; : &#39;不在线&#39;) . &#39;<br />&#39;;
// 可实现功能五:昨天和今天都上线的客户
$yestoday = Carbon::yesterday()->toDateString();
$yes_key = str_replace(&#39;-&#39;, &#39;&#39;, $yestoday);
$members = [];
Redis::pipeline(function ($pipe) use ($key, $yes_key, &$members) {
    Redis::zinterstore(&#39;new_key&#39;, [$key, $yes_key], [&#39;aggregate&#39; => &#39;min&#39;]);
    $members = Redis::zRangeByScore(&#39;new_key&#39;, &#39;-inf&#39;, &#39;+inf&#39;, [&#39;limit&#39; => [0, 50]]);
    //dump($members);
});
echo &#39;昨天和今天都上线的用户有:&#39;;
foreach ($members as $value) {
    echo $value . &#39; &#39;;
}

3 Use hyperloglog for statistics

Different from the ordered collection method, hyperloglog saves space very much, but the function it implements is also very simple and can only count. The number of people online cannot realize any other functions.

Redis HyperLogLog is an algorithm used for cardinality statistics. The advantage of HyperLogLog is that when the number or volume of input elements is very, very large, the space required to calculate the cardinality is always fixed and very small. .

In Redis, each HyperLogLog key only costs 12 KB of memory to calculate the cardinality of nearly 2^64 different elements. This is in sharp contrast to a collection that consumes more memory when calculating cardinality. The more elements there are, the more memory is consumed.

However, because HyperLogLog will only calculate the cardinality based on the input elements and will not store the input elements themselves, HyperLogLog cannot return each element of the input like a collection.

// note HyperLogLog 只需要知道在线总人数
for ($i=0; $i < 6; $i++) {
    $online_user_num = mt_rand(10000000, 99999999);     //模拟在线人数
    var_dump($online_user_num);
    for ($j=1; $j < $online_user_num; $j++) { 
        $user_id = mt_rand(1, 100000000);
        $redis->pfadd(&#39;002|online_users_day_&#39;.$i, [$user_id]);
    }
}
$count = 0;
for ($i=0; $i < 3; $i++) { 
    $count += $redis->pfcount(&#39;002|online_users_day_&#39;.$i);
    print_r($redis->pfcount(&#39;002|online_users_day_&#39;.$i). "\n");
}
var_dump($count);
//note  3 days total online num
var_dump($redis->pfmerge(&#39;002|online_users_day_both_3&#39;, [&#39;002|online_users_day_0&#39;, &#39;002|online_users_day_1&#39;, &#39;002|online_users_day_2&#39;]));
var_dump($redis->pfcount(&#39;002|online_users_day_both_3&#39;));

This solution can only count the total number of online people in a certain period of time, but cannot do anything about the list of online users, but it saves memory. When there are not many statistical data requirements, we You can consider this option.

4 Use bitmap statistics

Bitmap uses a bit to represent the value or status corresponding to an element, and the key is the corresponding element itself. We know that 8 bits can form a Byte, so the bitmap itself will greatly save storage space.

bitmap is commonly used for functions such as user check-in, active users, and online users.

The code is as follows

// 模拟当前用户
$uid = request(&#39;uid&#39;);
$key = &#39;online_bitmap_&#39; . date(&#39;Ymd&#39;);
// 设置当前用户在线
Redis::setBit($key, $uid, 1);
// 可实现功能1:在线人数
$c = Redis::bitCount($key);
echo &#39;在线人数:&#39; . $c . &#39;<br />&#39;;
// 可实现功能2:指定用户是否在线
$online = Redis::getBit($key, $uid);
echo $uid . ($online ? &#39;在线&#39; : &#39;不在线&#39;) . &#39;<br />&#39;;
// 可实现功能3:昨天和今天均上线的用户总数
$yestoday = Carbon::yesterday()->toDateString();
$yes_key = str_replace(&#39;-&#39;, &#39;&#39;, $yestoday);
$c = 0;
Redis::pipeline(function ($pipe) use ($key, $yes_key, &$c) {
    Redis::bitOp(&#39;AND&#39;, &#39;yest&#39;, $key, $yes_key);
    $c = Redis::bitCount(&#39;yest&#39;);
});
echo &#39;昨天和今天都上线的用户数量有:&#39; . $c . &#39;<br />&#39;;

bitmap does not consume much memory space, but provides a lot of statistical information. This solution is worth recommending.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of Detailed explanation of four methods to count the number of people online using PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment