<?
#Where to save settings
$CountFile = "count_data.dat";
#Kill IP Logs after xxx seconds coming
$KillSessionAfter = 24*60*60;
#Clear Old IPs every xxx seconds
$CheckLogEach = 5*60;
?>
<?
  $log = fopen("log.txt", "a");
  class _Counter
  {
    var $Ips=array();
    var $TotalCount = 0;
    var $UniqueCount = 0;
    var $LastChecked = 0;
    var $Version = 1;
    
    function ClearOld()
    {
      global $CheckLogEach, $KillSessionAfter;
      
      if ($this->LastChecked != 0 && $this->LastChecked > time() - $CheckLogEach)
        return;
      
      $this->LastChecked = time();
      for ($i=0; $i<count($this->Ips);)
      {
        $temp=array_keys($this->Ips);
        if (($this->Ips[$temp[$i]]) < (time() - $KillSessionAfter))
        {
          array_splice($this->Ips, $i, 1);
        }
        else
          $i++;
      }
    }
    
    function AddHit($Ip)
    {
      $isUnique = !isset($this->Ips[$Ip]);
      if ($isUnique)
        $this->UniqueCount++;
      $this->TotalCount++;
      $this->Ips[$Ip] = time();
      return $isUnique;
    }
  }
?>
<?
$Counter = new _Counter();

if (@is_readable($CountFile))
{
  $temp = unserialize(implode("", @file($CountFile)));
  if (!isset($temp->Version) || $temp->Version < $Counter->Version)
  {
    if (isset($temp->Ips))
      $Counter->Ips = $temp->Ips;
    if (isset($temp->TotalCount))
      $Counter->TotalCount = $temp->TotalCount;
    if (isset($temp->UniqueCount))
      $Counter->UniqueCount = $temp->UniqueCount;
    if (isset($temp->LastChecked))
      $Counter->LastChecked = $temp->LastChecked;
  }
  else
    $Counter = $temp;
}

$Counter->ClearOld();
if ($Counter->AddHit(!empty($REMOTE_ADDR)?$REMOTE_ADDR:'127.0.0.1'))
{
  fwrite($log, date('d.m.Y H:i').'> Hit from '.(!empty($REMOTE_HOST)?$REMOTE_HOST:'').' ('.(!empty($REMOTE_ADDR)?$REMOTE_ADDR:'127.0.0.1').")\n");
}

$s = serialize($Counter);
$fp = fopen($CountFile, "w+");
fputs($fp, $s);
fclose($fp);
fclose($log);

echo $Counter->UniqueCount;
return $Counter->UniqueCount;
?>