Backend Development 4 min read

Using Redis Bitmap for Online User Statistics in Laravel

This article explains how to efficiently count daily visits and online users in a Laravel application by leveraging Redis bitmap, detailing its memory‑saving advantages, providing complete PHP code for setting, counting, and checking online status, and comparing alternative methods such as tables, sorted sets, and HyperLogLog.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using Redis Bitmap for Online User Statistics in Laravel

In many web applications it is necessary to know the daily visit count and the number of users currently online, and this article presents a practical solution using Laravel and Redis bitmap.

Bitmap stores a bit for each user ID, allowing compact storage; 8 bits form a byte, so memory usage is minimal. It is commonly used for sign‑in, active users, and online user tracking.

The article provides a complete PHP code example that sets a user's online status with Redis::setBit , retrieves the total online count with Redis::bitCount , checks a specific user's status with Redis::getBit , and calculates users who were online both yesterday and today using Redis::bitOp('AND', ...) . The code is shown below:

<code>// Simulate current user
$uid = request('uid');
$key = 'online_bitmap_' . date('Ymd');
// Set current user online
Redis::setBit($key, $uid, 1);
// Function 1: online count
$c = Redis::bitCount($key);
echo '在线人数:' . $c . '<br />';
// Function 2: check if specific user is online
$online = Redis::getBit($key, $uid);
echo $uid . ($online ? '在线' : '不在线') . '<br />';
// Function 3: users online both yesterday and today
$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 />';
</code>

Besides bitmap, the article briefly mentions three alternative approaches: using a database table (suitable for low concurrency), using Redis sorted sets (higher memory consumption and requires explicit logout handling), and using HyperLogLog (memory‑efficient but only provides approximate counts without user lists).

Overall, bitmap offers a memory‑efficient and versatile way to count online users, making it a recommended solution for backend developers.

backendRedisBitmapLaravelOnline Users
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.