How many users are connected to a site.


/ Published in: PHP
Save to your folder(s)

Count how many users are connected to a site (execute this function in every page, put it in the header).


Copy this code and paste it in your HTML
  1. function getIP() {
  2. $ip="";
  3. if (getenv("HTTP_CLIENT_IP")) $ip = getenv("HTTP_CLIENT_IP");
  4. else if(getenv("HTTP_X_FORWARDED_FOR")) $ip = getenv("HTTP_X_FORWARDED_FOR");
  5. else if(getenv("REMOTE_ADDR")) $ip = getenv("REMOTE_ADDR");
  6. else $ip = "";
  7. return $ip;
  8. }
  9.  
  10. function howManyIps() {
  11. $filename = "./howmanyip.log";
  12. $seconds = 300;
  13. $yourIP = getIP();
  14.  
  15. if (file_exists($filename.".lock")) $readonly = true; else $readonly=false;
  16.  
  17. $count = 0;
  18. //lock the file
  19. if (!$readonly) $fpLock = fopen($filename".lock", "w");
  20.  
  21. //read data ips
  22. $fp = fopen($filename, "r");
  23. $arIPS=explode ("\n", fread($fp,filesize($filename)) );
  24. fclose($fp);
  25.  
  26. //if file is locked get out
  27. if ($readonly) return count($arIPS);
  28.  
  29. $s = "";
  30. $already=false;
  31. //update data and search user ip
  32. for ($i=0;$i<count($arIPS);$i++) {
  33.  
  34. $arData= explode (" ", $arIPS[$i]);
  35.  
  36. //update your user timer
  37. if ($yourIP==$arData[0]) {
  38. $already=true;
  39. $arData[1]=time();
  40. }
  41.  
  42. // check if user is old
  43. if ( time()- (integer)$arData[1] < $seconds ){
  44. $s.=$arData[0]." ".$arData[1]."\n";
  45. $count++;
  46. }
  47.  
  48. }
  49.  
  50. if (!$already) {
  51. //your user is new, add it to the list
  52. $s.=$yourIP." ".time()."\n";
  53. $count++;
  54. }
  55.  
  56. //save the list
  57. $fp = fopen($filename, "w");
  58. fwrite($fp,$s);
  59. fclose($fp);
  60.  
  61. //remove thr lock
  62. fclose($fpLock);
  63. unlink($filename.".lock");
  64.  
  65. return $count;
  66.  
  67. }

URL: http://www.barattalo.it/2009/12/03/how-many-users-are-connected/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.