PHP: Simple Active Users Counter

Simple Active Users Counter is a service to record and show number of recent active/online users.

Simple Active Users Counter does not use databases. The information is stored in files, but uses a different strategy to the one in other counters: when a user visits a page in our website, a file is created within a "counters" folder. The name of the file is the IP address of the user. For each user a new file is created, and the modification date of the file will correspond to the most recent activity of that specific user in the website. In case the visitor is not a new one, the file with that specific IP address will be overwritten, so a new 'most recent activity' will be recorded (which corresponds to the last modification date of the file). Recording user's last activity does not require reading information stored in a database or text file.

When counting number of recent visitors, all files in the "counters" folder are checked. In case the file has been created recently (for example in the last 5 minutes; this parameter is customizable) the file will be accounted as an active/online user. On the contrary, if the file is older, it will be deleted.

The procedure described for our Active Users Counter allows recording last activity of users without requiring reading the information in the database. Consequently, the webmaster may record information in all pages in the website, but the number of active users may be shown only in main page or in a limited number of pages, so that the computing and read/write activity will be limited to pages showing the number of active users.

As a consequence, Simple Active Users Counter may be consider as a simple (no databases) and fast (mostly for pages recording active users but not showing their number) service, but also a limited one(only active/online visitors are shown). Webmasters must decide whether showing number of active users is good enough for their websites. If so, this service is a good alternative.

Requeriments and code

To run this service, the following are required:

  • A folder must be created to store temporal files.
    In the code bellow, a random string is included in the name of the folder.
    You may create a folder name "users_WLL6fnVuTp " in the main directory of your site, or choose a different name.
  • A copy of file "active_users_record.php" (bellow) must be copied to the server.
    Our suggestion is to copy it to main directory of your site.
  • A copy of file "active_users.php" (bellow) must be also copied to the server.
    Again, our suggestion is to copy it to main directory of your site.
  • Code to be included in your pages:
    • In all PHP files you want to record users (but you do not want to show their number), the following code must be included.
      <? include($_SERVER["DOCUMENT_ROOT"]."/active_users_record.php); ?>
    • In all PHP files you want to record and show number of users, the following code must be included.
      <? include($_SERVER["DOCUMENT_ROOT"]."/active_users.php); ?>
    • The code bellow explains step by step the behaviour of the script.
      The code is totally functional, and in same places alternative options are shown (one of them is activated).
Code:
File 1:
active_users_record.php
<?

// ###############  SET UP THE VARIABLES  ########################################

// FOLDER USED TO STORE TEMPORAL FILES
//    IMPORTANT: the folder must have proper permissions to allow writing files
//    The name of the temporal files contains the IP address of the user
//    ($_SERVER["DOCUMENT_ROOT"] is the root folder for the website)
$folder=$_SERVER["DOCUMENT_ROOT"]."/users_WLL6fnVuTp/";


// ###############  THE WORKING PART OF THE SCRIPT ##############################

// DO NOT SHOW ERRORS TO VISITORS (just in case)
error_reporting(0);

// GET IP ADDRESS OF USER (a function in the bottom is used)
$ip=getIP();

// REGISTER THE USER
//      A file will be created. The name of the file will contain the IP of the user.
//      In case the file already exists, it will be overwritted.
//      The creation time of the file will indicate how long ago the user
//              with this IP visited a page containing this active users counter
        // OPTION 1, for PHP4 or superior
        $cf = fopen($folder.$ip, "w");
        fwrite($cf, "");
        fclose($cf);
        // OPTION 2, for PHP5 or superior
        // file_put_contents ($folder."$ip.txt", "0");

// ########################  FUNCTIONS  #########################################
// funtion getIP will be used to get IP address of visitor
function getIP() {
        // Option 1 to get the IP address of visitor
        //      if a value for $_SERVER['HTTP_X_FORWARDED_FOR'] is available
        //      $ip is obtained and returned
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
                $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
                return $ip;
        }
        // Option 2 to get the IP address of visitor
        //      if a value for $_SERVER['REMOTE_ADDR'] is available
        //      $ip is obtained and returned
        if(isset($_SERVER['REMOTE_ADDR'])){
                $ip = $_SERVER['REMOTE_ADDR'];
                return $ip;
        }
        // IP has not been obtained, so a default IP is returned
        //      The default value will be used very few times, so
        return "0.0.0.0";
}

?>

File2:
active_users.php
<?

// ###############  SET UP THE VARIABLES  ########################################

// FOLDER USED TO STORE TEMPORAL FILES
//    IMPORTANT: the folder must have proper permissions to allow writing files
//    The name of the temporal files contains the IP address of the user
//    ($_SERVER["DOCUMENT_ROOT"] is the root folder for the website)
$folder=$_SERVER["DOCUMENT_ROOT"]."/users_WLL6fnVuTp/";

// TIME SINCE LAST ACTIVITY OF AN USERS TO BE CONSIDERED NON-ACTIVE
$timeold=300;   // seconds

// ###############  THE WORKING PART OF THE SCRIPT ##############################

// DO NOT SHOW ERRORS TO VISITORS (just in case)
error_reporting(0);

// GET ACTUAL TIME
$actualtime=date("U");   // seconds since January 1st, 1970.

// GET IP ADDRESS OF USER (a function in the bottom is used)
$ip=getIP();

// REGISTER THE USER
//      A file will be created. The name of the file will contain the IP of the user.
//      In case the file already exists, it will be overwritted.
//      The creation time of the file will indicate how long ago the user
//              with this IP visited a page containing this active users counter
        // OPTION 1, for PHP4 or superior
        $cf = fopen($folder.$ip, "w");
        fwrite($cf, "");
        fclose($cf);
        // OPTION 2, for PHP5 or superior
        // file_put_contents ($folder."$ip.txt", "0");

// COUNT NUMBER OF ACTIVE USERS
//      All files within folder $folder will be checked
//      Files $timeold seconds old (defined above) will be deleted
//      Files created up to $timeold seconds ago will be accounted as active users

        // a counter; no users at this moment
        $counter=0;
        // get the list of files within $folder
        $dir = dir($folder);
        // check all files one by one (variable $temp will be the name of each file)
        while($temp = $dir->read()){
                // the ones bellow are not files, so continue to next $temp
                if ($temp=="." or $temp==".."){continue;}
                // For real files, get the last modification time
                //   (number of seconds since January 1st, 1970)
                //    and save the data to variable $filecreatedtime
                $filecreatedtime=date("U", filemtime($folder.$temp));
                // check whether the file is $timeold seconds old
                if ($actualtime>($filecreatedtime+$timeold)){
                        // the file IS old, so delete it
                        unlink ($folder.$temp);                                                                   //
                }else{
                        // the file IS NOT old, so an active user will be accounted
                        $counter++;
        }
}
// DISPLAY NUMBER OF ACTIVE USERS
        // Option 1  (displays only the number of active users)
        //print "Users online: $counter";
        // Option 2  (displays number of active users, and defines how old an active user is in seconds).
        // print "Users online: $counter (in last $timeold seconds)";
        // Option 3  (displays number of active users, and defines how old an active user is in minutes).
        $minutes=round($timeold/60);
        print "Users online: $counter (in last $minutes minutes)";

// ########################  FUNCTIONS  #########################################
// funtion getIP will be used to get IP address of visitor
function getIP() {
        // Option 1 to get the IP address of visitor
        //      if a value for $_SERVER['HTTP_X_FORWARDED_FOR'] is available
        //      $ip is obtained and returned
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
                $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
                return $ip;
        }
        // Option 2 to get the IP address of visitor
        //      if a value for $_SERVER['REMOTE_ADDR'] is available
        //      $ip is obtained and returned
        if(isset($_SERVER['REMOTE_ADDR'])){
                $ip = $_SERVER['REMOTE_ADDR'];
                return $ip;
        }
        // IP has not been obtained, so a default IP is returned
        //      The default value will be used very few times, so
        return "0.0.0.0";
}

?>


 

PHPTutorial.info.