This article mainly introduces php's method of accurately counting the number of online users. For more information, see this method, if you want to know how to implement it, please read it with patience.
<? 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 the REQUEST fails, false $ nowtime =$ _ SERVER ['request _ time'] is returned; $ 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 no COOKIE exists, it is the first access $ vid = 0; // initialize the visitor ID do {// 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.