且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Google Analytics 在网站上显示实时用户数

更新时间:2023-12-02 15:52:52

正如 Trott 之前所解释的,分析中没有这样的功能.但是,我给你一个非常非常古老的选择.我是在 2004 年写的,所以它已经过时了,但基本上有效.此外,它在不使用任何数据库的情况下工作......有时你需要像这样的复古解决方案:)

As Trott explained before, there is no such function in analytics. However, I give you a very very old alternative. I wrote this in 2004, so its outdated, but basically works. Also, it works without using any databases.. sometimes you need retro-solutions like this :)

现场演示:kopli.pri.ee/***/6976362.php

(您需要为当前文件夹设置 777 chmod,以便自动创建 users.dat)

<?php
$current_users_file = 'users.txt';
if (!file_exists($current_users_file)) fclose(fopen($current_users_file, "w"));
$users = file($current_users_file);
$found = false;
$user_count = count($users);
$fp = fopen($current_users_file, "w");
foreach($users as $user) {
    $user = explode("|", $user);
    if ($user[1]+300 < time()) {
        $user_count--;
        continue;
    } elseif ($user[0] == $REMOTE_ADDR) {
        $user[1] = time();
        $found = true;
    }
    $user = trim(implode("|", $user))."
";
    fputs($fp, $user);
}
if (!$found) {
    fputs($fp, $REMOTE_ADDR."|".time()."
");
    $user_count++;
}
fclose($fp);
echo 'Active users <b>' . $user_count . '</b>';
?>