The following share a simple way to use PHP to calculate the current number of online Web site, but simply by calculating the visitor IP address to arrive at a rough result, can not accurately calculate the current number of online, the accuracy of the request can refer to the site article:
PHP statistics online numbers, accurate statistics online number of ways
<?php
header (' content-type:text/html; Charset=utf-8 ');
author:www.Alixixi.com
$online _log= ' count.txt ';//Save online number of data files
, $timeout =45;//45 seconds without action, is recognized as a drop
$entries =file ($ Online_log);//returns the file as an array, each cell in the array is the corresponding row in the file, including the newline character
$temp =array ();
For ($i =0 $i <count ($entries); $i + +) {
$entry =explode (', ', trim ($entries [$i]));
if ($entry [0]!=getenv (' remote_addr ')) && ($entry [1]>time ())] {
Array_push ($temp, $entry [0]. $ ENTRY[1]. ' n ');//Remove other viewer's information, and remove timeout, save into $temp
}
Array_push ($temp, getenv (' remote_addr '). Time () + ($timeout)). " \ n ")//Update the viewer's time
$users _online=count ($temp);//Calculate online number
$entries =implode (", $temp);
Write file
$fp =fopen ($online _log, ' W ');
Flock ($FP, LOCK_EX);//note flock () cannot work properly in NFS and some other network file systems
fputs ($FP, $entries);
Flock ($FP, lock_un);
Fclose ($FP);
Echo ' currently has '. $users _online. ' People online ';