Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

开源php统计(php在线人数源码)

作者:农村混血兒   发布日期:2025-06-01   浏览:242

以下是一个简单的PHP在线人数统计的开源代码示例:

index.php:

<?php
session_start();

// 更新在线用户数
function updateOnlineUsers() {
    $timeout = 300; // 在线超时时间(秒)
    $file = 'online_users.txt'; // 保存在线用户的文件

    if (file_exists($file)) {
        $users = unserialize(file_get_contents($file));
        $updatedUsers = array();

        foreach ($users as $user) {
            if (time() - $user['timestamp'] < $timeout) {
                $updatedUsers[] = $user;
            }
        }

        // 添加当前用户到在线用户列表
        $updatedUsers[] = array(
            'id' => session_id(),
            'ip' => $_SERVER['REMOTE_ADDR'],
            'timestamp' => time()
        );

        file_put_contents($file, serialize($updatedUsers));
    } else {
        // 创建新的在线用户列表文件并添加当前用户
        $users = array(
            array(
                'id' => session_id(),
                'ip' => $_SERVER['REMOTE_ADDR'],
                'timestamp' => time()
            )
        );

        file_put_contents($file, serialize($users));
    }
}

// 获取在线用户数
function getOnlineUsersCount() {
    $timeout = 300; // 在线超时时间(秒)
    $file = 'online_users.txt'; // 保存在线用户的文件

    if (file_exists($file)) {
        $users = unserialize(file_get_contents($file));
        $count = 0;

        foreach ($users as $user) {
            if (time() - $user['timestamp'] < $timeout) {
                $count++;
            }
        }

        return $count;
    }

    return 0;
}

// 更新在线用户数
updateOnlineUsers();

// 获取在线用户数
$onlineUsersCount = getOnlineUsersCount();
?>

<!DOCTYPE html>
<html>
<head>
    <title>在线人数统计</title>
</head>
<body>
    <h1>当前在线人数:<?php echo $onlineUsersCount; ?></h1>
</body>
</html>

使用方法:

  1. 创建一个名为online_users.txt的空文本文件,并确保该文件可写入;
  2. 将上述代码保存为index.php文件;
  3. index.php文件上传到你的PHP服务器;
  4. 在浏览器中访问index.php文件,即可看到当前在线人数。

注意事项:

  • 该代码使用session来识别用户,确保你的PHP服务器已启用session
  • 在线用户的超时时间可以根据需要进行调整,单位为秒;
  • 该代码只提供了基本的在线人数统计功能,如需更复杂的统计功能,可以根据需求进行修改和扩展。

上一篇:php取消错误显示(php忽略警告)

下一篇:php 判断输入内容数字?(php判断数字在指定范围内)

大家都在看

php session用法

phpisset函数

php后端

php爬虫框架

php读取csv文件

php 三元表达式

php文件加密

php 拆分字符串

php pcntl

php ||

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站