This article describes how to accurately count the number of online users in php. For more information, see
This article describes how to accurately count the number of online users in php. For more information, see
This is a very accurate method for counting the number of online users through php. Please read it with patience if you want to know how to implement it.
<? Php program filename='online.txt '; // data file $ cookiename = 'vgotcn _ OnLineCount'; // cookie name $ onlinetime = 600; // online validity period, in the unit: seconds (600 equals 10 minutes) $ online = file ($ filename); // The PHP file () function reads the entire file into an array. Similar to file_get_contents (), file () returns the object as an array. Each unit in the array is a corresponding line in the file, including line breaks. If it fails, false $ nowtime = $ _ SERVER ['request _ time']; $ nowonline = array (); // obtain the still valid data foreach ($ online as $ line) {$ row = explode ('|', $ line ); $ sesstime = trim ($ row [1]); if ($ nowtime-$ sesstime) <= $ onlinetime) {// if it is still in effect, the data is saved. Otherwise, $ nowonline [$ row [0] = $ sesstime; // retrieves the online list to the array. The session ID is the key name, the last communication time is key value}/* @ create visitor communication status use cookie communication COOKIE will expire when the browser is closed, but if the browser is not closed, this COOKIE will remain valid, until the online time set by the program times out */if (isset ($ _ COOKIE [$ cookiename]) {// If a COOKIE exists, that is, it is not the first access, no people are added and the communication time is updated. $ uid =$ _ COOKIE [$ cookiename];} else {// if there is no COOKIE, it is the first access $ vid = 0; // initialize the visitor IDdo {// give the user a new ID $ vid ++; $ uid = 'u '. $ vid;} while (array_key_exists ($ uid, $ nowonline); setcookie ($ cookiename, $ uid);} $ nowonline [$ uid] = $ nowtime; // update current time status // count current online users $ total_online = count ($ nowonline); // write data if ($ fp = @ fopen ($ filename, 'W') {if (flock ($ fp, LOCK_EX) {rewind ($ fp); foreach ($ nowonline as $ fuid => $ ftime) {$ fline = $ fuid. '| '. $ ftime. "\ n"; @ fputs ($ fp, $ fline);} flock ($ fp, LOCK_UN); fclose ($ fp) ;}} echo 'document. write ("'. $ total_online. '");';
I hope this article will help you learn php programming.