How PHP Gets the current number of people online

Source: Internet
Author: User
Tags array count flock

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 ';


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.