search
HomeBackend DevelopmentPHP Tutorial大神都是如何查看网页的同时在线人数啊?

  1. 网页后台是基于PHP+Mysql+Redis+Nginx的,想问下查看网页同时在线(同时查看网页)的人数有多少,有什么方案呀?

回复内容:

  1. 网页后台是基于PHP+Mysql+Redis+Nginx的,想问下查看网页同时在线(同时查看网页)的人数有多少,有什么方案呀?

这里有个基于workerman开发的非常精确的统计在线人数的开源组件 http://www.workerman.net/web-sender

效果:
能够非常实时的统计在线用户数,甚至统计用户目前打开了多少个页面。效果如下
大神都是如何查看网页的同时在线人数啊?

在线demo见http://www.workerman.net/页面底部

原理
原理是页面打开后js建立一个与服务端的socket长连接,页面通过这个socket连接发送一个uid登录请求,服务端就知道这个连接是哪个用户的,如果用户的所有连接都关闭了,说明用户下线。同时根据有多少个socket连接,就知道整个网站有多少页面正在开着。由于是socket可以实时监测到连接事件和连接断开事件,所以非常数据是非常实时的。服务端采用workerman,非轮询,性能非常高。

服务端使用方法
下载后直接在命令行 php start.php start -d
启动界面类似如下:
大神都是如何查看网页的同时在线人数啊?

客户端使用方法

<script src='//cdn.bootcss.com/socket.io/1.3.7/socket.io.js'></script>
<script>
var socket = io('http://'+服务端ip+':3120');
socket.on('connect', function(){socket.emit('login', '<?php echo session_id();?>');});
socket.on('update_online_count', function(count){$('#online_count').html(count);});
</script>

其它
这个组件不仅可以统计在线用户数据,更强大的是可以在服务端向任意用户的网页实时推送数据,效果类似如下

大神都是如何查看网页的同时在线人数啊?

实时性要求不那么高的话,就基于当前有效的session数量(基于cookie)

实时性要求高的话,使用websocket统计连接数

首先,得确定一下什么是在线,简单的做法就是固定时间比如5分钟内活动的都算在线。
剩下的就简单咯,记录一下用户最后活跃时间(页面刷新或者ajax都行),需要统计时count出距离当前时间

记录Session数量即可

  1. 统计session数量,统计时间跨度取决于session生命期。

  2. 利用文件+cookie,循环遍历文件中cookie个数。 不过既然你有redis,也可以直接用redis 替代文件读写。
    php统计在线人数

我们不用cookie和服务器端session,但刚好有这个需求,最后是用websocket看的,原以为很麻烦,没想到还挺容易的

我常用的一个方法:

1、 建立一张 mysql 的内存表(优秀的读写性能以及快速增删)

<code>CREATE TABLE `xx_session` (
  `user_id` INT(10) UNSIGNED NOT NULL DEFAULT '0',
  `expire` INT(10) UNSIGNED NOT NULL DEFAULT '0',
  `ip` INT(10) UNSIGNED NOT NULL DEFAULT '0',
  PRIMARY KEY (`user_id`),
  KEY `ip` (`ip`),
  KEY `expireIndex` (`expire`)
) ENGINE=MEMORY DEFAULT CHARSET=utf8
</code>
  • user_id:用户id

  • expire:用于告诉系统过期时间

  • ip:ip2long 转成的整型ip

附:内存表有一个问题,就是重启后所有数据会消失。这点在使用中请务必注意。

2、用户每次操作时 replace into 进内存表:

<code>REPLACE INTO xx_session (user_id, expire, ip)VALUES(10, 1000000000, 102933800);</code>

3、 用户退出时:

<code>DELETE FROM xx_session WHERE user_id=10;</code>

4、 在线用户过期,可以通过 Mysql 的 Event Scheduler 来定时删除过期用户:

<code>CREATE DEFINER=`root`@`%` EVENT `30minute` ON SCHEDULE EVERY 30 MINUTE STARTS '2012-05-30 00:00:00' ON COMPLETION NOT PRESERVE ENABLE DO BEGIN
        DELETE FROM xx_session WHERE expire</code>

注意:
mysql 要启用 Event Scheduler:

查看是否启动:

<code>SELECT @@event_scheduler;</code>

启动方法1(不重启,但重启失效):

<code>SET GLOBAL event_scheduler = 1;</code>

启动方法2(永久生效),在 mysql 启动时加上:

<code>mysqld ... --event_scheduler=1</code>

启动方法3(永久生效),在 my.cnf 中、[mysqld]里,加入:

<code>event_scheduler=ON</code>
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software