Active Users (A PHP Script)

A member of a forum I frequent needed an active users online script so I wrote up the below for him.  It’s an overdone and unoriginal script but maybe someone will find it useful.

<?php
 
$CONFIG = array ();
$CONFIG["visitor_file"] = "visitors.txt";
$CONFIG["timeout"] = 60;
 
if (file_exists ($CONFIG["visitor_file"]))
{
  $curData = unserialize (file_get_contents ($CONFIG["visitor_file"]));
  $curTime = time ();
 
  $newData = array ();
  $userInFile = false;
 
  if (count ($curData) > 0)
  {
    foreach ($curData as $ip => $timeOfLastVisit)
    {
      if ($curTime - $timeOfLastVisit >= $CONFIG["timeout"])
      {
        continue;
      }
 
      if ($ip == $_SERVER["REMOTE_ADDR"])
      {
        $userInFile = true;
        $newData[$ip] = time ();
      }
      else
      {
        $newData[$ip] = $timeOfLastVisit;
      }
    }
  }
}
 
if (!isset ($newData) || count ($newData) == 0 || (isset ($userInFile) && !$userInFile))
{
  $newData[$_SERVER["REMOTE_ADDR"]] = time ();
}
 
file_put_contents ($CONFIG["visitor_file"], serialize ($newData));
 
echo count ($newData);
 
?>

Leave A Comment

Please be polite. We appreciate that. Your email address will not be published and required fields are marked

This site uses Akismet to reduce spam. Learn how your comment data is processed.