A php code that accurately counts the number of online users
Using filename='online.txt '; // data file
- $ Cookiename = 'vgotcn _ onlinecount'; // cookie name
- $ Onlinetime = 600; // online validity period, in seconds (that is, 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 is returned.
- $ Nowtime = $ _ SERVER ['request _ time'];
- $ Nowonline = array ();
// Obtain valid data
- Foreach ($ online as $ line ){
- $ Row = explode ('|', $ line );
- $ Sesstime = trim ($ row [1]);
- If ($ nowtime-$ sesstime) <= $ onlinetime) {// if the time is still valid, the data will be saved. Otherwise, the data will not be counted.
- $ Nowonline [$ row [0] = $ sesstime; // gets the online list to the array. the session ID is the key name, and the last communication time is the key value.
- }
- }
/*
- @ Create a visitor's communication status
- Use cookies for communication
- The COOKIE will expire when the browser is closed, but if the browser is not closed, the COOKIE will remain valid until the online time set by the program times out.
- */
- If (isset ($ _ COOKIE [$ cookiename]) {// if there is a COOKIE that is not the first access, no people are added and the communication time is updated
- $ Uid = $ _ COOKIE [$ cookiename];
- } Else {// The first access if no COOKIE exists
- $ 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 the current time status
// Count the number of 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 .'");';
- ?>
|