Home >Backend Development >PHP Tutorial >A simple method to count the number of people online in php
The example in this article describes how to simply count the number of people online in PHP. Share it with everyone for your reference, the details are as follows:
<?php //首先你要有读写文件的权限 //本程序可以直接运行,第一次报错,以缶涂梢? $online_log = "count.dat"; //保存人数的文件, $timeout = 30;//30秒内没动作者,认为掉线 $entries = file($online_log); $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"); //取出其他浏览者的信息,并去掉超时者,保存进$temp } } array_push($temp,getenv('REMOTE_ADDR').",".(time() + ($timeout))."\n"); //更新浏览者的时间 $users_online = count($temp); //计算在线人数 $entries = implode("",$temp); //写入文件 $fp = fopen($online_log,"w"); flock($fp,LOCK_EX); //flock() 不能在NFS以及其他的一些网络文件系统中正常工作 fputs($fp,$entries); flock($fp,LOCK_UN); fclose($fp); echo "当前有".$users_online."人在线"; ?>
Usage:
Save the above code as count.php, where you want to use it:
include("count.php");
More interested in PHP related content Readers can check out the special topics on this site: "Summary of PHP File Operations", "Summary of PHP Operations and Operator Usage", "Summary of PHP Network Programming Skills", "Introduction Tutorial on PHP Basic Grammar", "Summary of PHP Office Document Operation Skills (Including Word , excel, access, ppt)", "php date and time usage summary", "php object-oriented programming introductory tutorial", "php string (string) usage summary", "php+mysql database operation introductory tutorial" and "php+mysql database operation introductory tutorial" Summary of common database operation skills in PHP》
I hope this article will be helpful to everyone in PHP programming.
The above introduces the method of simply counting the number of people online in PHP, including the methods of PHP. I hope it will be helpful to friends who are interested in PHP tutorials.