November 21, 2010

PHP – Visitors Online Counter

Question by anon445699

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;
}
?>

Answer by Starx

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.

...

Please fill the form - I will response as fast as I can!