A more accurate PHP code that counts the number of people online

WBOY
Release: 2016-07-25 09:05:34
Original
1065 people have browsed it
  1. $filename='online.txt';//Data file

  2. $cookiename='VGOTCN_OnLineCount';//Cookie name
  3. $onlinetime=600;//Online valid Time, unit: seconds (that is, 600 equals 10 minutes)
  4. $online=file($filename);

  5. //PHP file() function reads the entire file into an array. Similar to file_get_contents(), except file() returns the file as an array. Each cell in the array is a corresponding line in the file, including newlines. If it fails, return false

  6. $nowtime=$_SERVER['REQUEST_TIME'];
  7. $nowonline=array();

  8. //Get the data that is still valid

  9. foreach($online as $ line){
  10. $row=explode('|',$line);
  11. $sesstime=trim($row[1]);
  12. if(($nowtime - $sesstime)<=$onlinetime){//if If it is still within the valid time, the data will continue to be saved, otherwise it will be abandoned and no longer counted
  13. $nowonline[$row[0]]=$sesstime;//Get the online list into the array, the session ID is the key name, and the last communication time is the key Value
  14. }
  15. }

  16. /*

  17. @Create visitor communication status
  18. Use cookies to communicate
  19. COOKIE will become invalid 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
  20. */
  21. if(isset($_COOKIE[$cookiename])){//If there is a COOKIE, that is, it is not the first visit, the number of people will not be added and the communication time will be updated
  22. $uid=$_COOKIE[$ cookiename];
  23. }else{//If there is no COOKIE, it is the first visit
  24. $vid=0;//Initialize the visitor ID
  25. do{//Give the user a new ID
  26. $vid++;
  27. $uid='U'. $vid;
  28. }while(array_key_exists($uid,$nowonline));
  29. setcookie($cookiename,$uid);
  30. }
  31. $nowonline[$uid]=$nowtime;//Update the current time status
  32. //Count the number of people online now

  33. $total_online=count($nowonline);

  34. //Write data

  35. if($fp=@fopen($filename, 'w')){
  36. if(flock($fp,LOCK_EX)){
  37. rewind($fp);
  38. foreach($nowonline as $fuid=>$ftime){
  39. $fline=$fuid.'|' .$ftime."n";
  40. @fputs($fp,$fline);
  41. }
  42. flock($fp,LOCK_UN);
  43. fclose($fp);
  44. }
  45. }
  46. echo 'document.write("' .$total_online.'");';
  47. ?>

Copy code


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template