


Detailed 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.
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
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 '当前在线人数:' . $c . '<br />'; // 可实现功能二:某时间段内在线人数 $begin_date = '2020-08-13 09:00:00'; $end_date = '2020-08-13 18:00:00'; $c = DB::table('user_login') ->where('create_time', '>=', $begin_date) ->where('create_time', '<=', $end_date) ->count(); echo $begin_date . '-' . $end_date . '在线人数:' . $c . '<br />'; // 可实现功能三:最新上线的用户 $newest = DB::table('user_login') ->orderBy('create_time', 'DESC') ->limit(10) ->get(); echo '最新上线的用户有:'; foreach ($newest as $value) { echo $value->username . ' '; } echo '<br />'; // 可实现功能四:指定用户是否在线 $username = 'user_1111'; $online = DB::table('user_login') ->where('username', $username) ->exists(); echo $username . ($online ? '在线' : '不在线');
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 . '<br />'; // 按日期生成key $day = date('Ymd'); $key = 'online:' . $day; // 是否在线 $is_online = Redis::zScore($key, $client_id); if (empty($is_online)) { // 不在线,加入当前客户端 Redis::zAdd($key, time(), $client_id); } // 可实现功能一:当前总共在线人数 $c = Redis::zCard($key); echo '当前在线人数:' . $c . '<br />'; // 可实现功能二:某时间段内在线人数 $begin_date = '2020-08-13 09:00:00'; $end_date = '2020-08-13 18:00:00'; $c = Redis::zCount($key, strtotime($begin_date), strtotime($end_date)); echo $begin_date . '-' . $end_date . '在线人数:' . $c . '<br />'; // 可实现功能三:最新上线的用户,时间从小到大排序 $newest = Redis::zRangeByScore($key, '-inf', '+inf', ['limit' => [0, 50]]); echo '最新上线的用户有:'; foreach ($newest as $value) { echo $value . ' '; } echo '<br />'; // 可实现功能四:指定用户是否在线 $username = $client_id; $online = Redis::zScore($key, $client_id);; echo $username . ($online ? '在线' : '不在线') . '<br />'; // 可实现功能五:昨天和今天都上线的客户 $yestoday = Carbon::yesterday()->toDateString(); $yes_key = str_replace('-', '', $yestoday); $members = []; Redis::pipeline(function ($pipe) use ($key, $yes_key, &$members) { Redis::zinterstore('new_key', [$key, $yes_key], ['aggregate' => 'min']); $members = Redis::zRangeByScore('new_key', '-inf', '+inf', ['limit' => [0, 50]]); //dump($members); }); echo '昨天和今天都上线的用户有:'; foreach ($members as $value) { echo $value . ' '; }
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('002|online_users_day_'.$i, [$user_id]); } } $count = 0; for ($i=0; $i < 3; $i++) { $count += $redis->pfcount('002|online_users_day_'.$i); print_r($redis->pfcount('002|online_users_day_'.$i). "\n"); } var_dump($count); //note 3 days total online num var_dump($redis->pfmerge('002|online_users_day_both_3', ['002|online_users_day_0', '002|online_users_day_1', '002|online_users_day_2'])); var_dump($redis->pfcount('002|online_users_day_both_3'));
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('uid'); $key = 'online_bitmap_' . date('Ymd'); // 设置当前用户在线 Redis::setBit($key, $uid, 1); // 可实现功能1:在线人数 $c = Redis::bitCount($key); echo '在线人数:' . $c . '<br />'; // 可实现功能2:指定用户是否在线 $online = Redis::getBit($key, $uid); echo $uid . ($online ? '在线' : '不在线') . '<br />'; // 可实现功能3:昨天和今天均上线的用户总数 $yestoday = Carbon::yesterday()->toDateString(); $yes_key = str_replace('-', '', $yestoday); $c = 0; Redis::pipeline(function ($pipe) use ($key, $yes_key, &$c) { Redis::bitOp('AND', 'yest', $key, $yes_key); $c = Redis::bitCount('yest'); }); echo '昨天和今天都上线的用户数量有:' . $c . '<br />';
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
