search
HomeBackend DevelopmentPHP Tutorialphp获取网站当前在线人数的方法

一、利用php实现简单的计算当前网站在线人数的方法,只是简单的通过计算访问者ip地址从而得出一个大致的结果,不能精确的计算当前在线人数。

<p><?php</p>header('Content-type: text/html; charset=utf-8');<br />//author:www.scutephp.com<br />$online_log='count.txt';//保存在线人数数据的文件, <br />$timeout=45;//45秒内没有动作,则被认识是掉线 <br />$entries=file($online_log);//将文件作为一个数组返回,数组中的每个单元都是文件中相应的一行,包括换行符在内<br />$temp=array();<br />for($i=0;$i<count($entries);$i++){<br />	$entry=explode(',',trim($entries[$i]));<br />	if(($entry[0]!=getenv('REMOTE_ADDR'))&&($entry[1]>time())){<br />		array_push($temp,$entry[0].','.$entry[1].'n');//取出其他浏览者的信息,并去掉超时者,保存进$temp <br />	}<br />}<br />array_push($temp,getenv('REMOTE_ADDR').','.(time()+($timeout))."\n");//更新浏览者的时间 <br />$users_online=count($temp);//计算在线人数<br />$entries=implode('',$temp);<br />//写入文件 <br />$fp=fopen($online_log,'w');<br />flock($fp,LOCK_EX);//注意 flock() 不能在NFS以及其他的一些网络文件系统中正常工作 <br />fputs($fp,$entries);<br />flock($fp,LOCK_UN);<br />fclose($fp);<br /><p>echo '当前有'.$users_online.'人在线';

二、利用php比较精确的统计在线人数的办法,注意这里所说的精确是指个数,如果需要精确在时间上,则需要根据实际情况调整代码中的有效时间。

<?php<br />//author:www.scutephp.com<br />$filename='online.txt';//数据文件<br />$cookiename='VGOTCN_OnLineCount';//cookie名称<br />$onlinetime=600;//在线有效时间,单位:秒 (即600等于10分钟)<br /><br />$online=file($filename);<br />//PHP file() 函数把整个文件读入一个数组中。与 file_get_contents() 类似,不同的是 file() 将文件作为一个数组返回。数组中的每个单元都是文件中相应的一行,包括换行符在内。如果失败,则返回 false<br />$nowtime=$_SERVER['REQUEST_TIME'];<br />$nowonline=array();<br />//得到仍然有效的数据<br />foreach($online as $line){<br />	$row=explode('|',$line);<br />	$sesstime=trim($row[1]);<br />	if(($nowtime - $sesstime)<=$onlinetime){//如果仍在有效时间内,则数据继续保存,否则被放弃不再统计<br />		$nowonline[$row[0]]=$sesstime;//获取在线列表到数组,会话ID为键名,最后通信时间为键值<br />	}<br />}<br />/*<br />@创建访问者通信状态<br />使用cookie通信<br />COOKIE 将在关闭浏览器时失效,但如果不关闭浏览器,此 COOKIE 将一直有效,直到程序设置的在线时间超时<br />*/<br />if(isset($_COOKIE[$cookiename])){//如果有COOKIE即并非初次访问则不添加人数并更新通信时间<br />	$uid=$_COOKIE[$cookiename];<br />}else{//如果没有COOKIE即是初次访问<br />	$vid=0;//初始化访问者ID<br />	do{//给用户一个新ID<br />		$vid++;<br />		$uid='U'.$vid;<br />	}while(array_key_exists($uid,$nowonline));<br />	setcookie($cookiename,$uid);<br />}<br />$nowonline[$uid]=$nowtime;//更新现在的时间状态<br />//统计现在在线人数<br />$total_online=count($nowonline);<br />//写入数据<br />if($fp=@fopen($filename,'w')){<br />	if(flock($fp,LOCK_EX)){<br />		rewind($fp);<br />		foreach($nowonline as $fuid=>$ftime){<br />			$fline=$fuid.'|'.$ftime."\n";<br />			@fputs($fp,$fline);<br />		}<br />		flock($fp,LOCK_UN);<br />		fclose($fp);<br />	}<br />}<br />echo 'document.write("'.$total_online.'");';


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft