PHP - Visitors Online Counter

2020-05-02 11:57发布

I have the following code to count visitors on my PHP site. It works fine on my local development machine using WampServer but when I uploaded my files to my hosting account for testing I realized that it does not work properly.

I get really high number count and also noticed the session are never deleted so they just keep accumulating.

It is a simple session counter. Is there a better way of doing it? Could some one please show me or point me to some article? Thank you!

<?php
//------------------------------------------------------------
// VISITORS ONLINE COUNTER
//------------------------------------------------------------
if (!isset($_SESSION)) {
  session_start();
}
function visitorsOnline()
{
    $session_path = session_save_path();
    $visitors = 0;
    $handle = opendir($session_path);

    while(( $file = readdir($handle) ) != false)
    {
        if($file != "." && $file != "..")
        {
            if(preg_match('/^sess/', $file))
            {
                $visitors++;
            }
        }
    }

    return $visitors;
}
?>

5条回答
我命由我不由天
2楼-- · 2020-05-02 12:28

If you want your own internal counting system then I would suggest, storing such information related to website in database. And update the record everytime a user browses the website.

查看更多
等我变得足够好
3楼-- · 2020-05-02 12:40

If this is shared hosting, you're counting everyone's session files, not just your own. That's why the number is huge and largely unrelated to how many people are on your site.

查看更多
一纸荒年 Trace。
4楼-- · 2020-05-02 12:41

Hmm, I'm not sure that reading the session files in the session dir is the best method.

Why not have a write on a db table for every page load. Then have a read that counts the number of unique users in the last x minutes?

It sounds db intensive but unless your site is ultra-busy, I can't see a problem.

查看更多
做个烂人
5楼-- · 2020-05-02 12:46

The best (free) way to count visitors is here: http://www.google.com/analytics.

If you want more realtime data, (for instance, currently active users) try: http://www.woopra.com/

If you're set on maintaining who is active on your site with your own code, I'd do so with a "last action" date field in your database on the users table. You will be able to do a PHP equivalent query to SELECT COUNT(id) FROM Users WHERE #{Time.now} > #{15.minutes.ago}

If you want to track anonymous users as well, rather than using the Users table, make a table with the visitor's IP as the identifying field and use the same technique mentioned above.

查看更多
家丑人穷心不美
6楼-- · 2020-05-02 12:52

If the problem on the production server is that sessions are simply never deleted, you have two options:

  • Lower the session expiry time on your PHP installation.
  • Examine the last-modified date of the session files and only count them towards your total if they were modified within a certain amount of time from now.
查看更多
登录 后发表回答