How many visitors browsing the site at the moment?

Sep 30, 2009 Author: Dr_ViRuS

This tutorial will show you how to make a class that will show how many users browsing the site at the moment.

First, how work this class and its function. For his realization normally need a Apache server, PHP, MySQL and desire to do that. The principle of work / performance is very simple:

Check whether the user is registered in the database. If a record is entered. If you subscribed to update the access time. Checking other records if the access time and now time. If the difference is greater than the given limit to remove all records with a limit expired.

Enough talk time for a little coding will explain each method if you have any questions feel free to write in the comments below. To start, you should create the table that we need to record. The table has 4 fields:

Table: usersonline usersonline_id - number of id (int) usersonline_session - hash of the session (varchar 100) length depends on the configuration of PHP usersonline_time - last access time (int) will record as timestamp usersonline_ipaddress-ip address of the user (varchar 25)

CREATE TABLE `usersonline` (
  `usersonline_id` INTEGER(11) NOT NULL AUTO_INCREMENT,
  `usersonline_session` VARCHAR(100) COLLATE utf8_general_ci NOT NULL,
  `usersonline_time` INTEGER(11) DEFAULT NULL,
  `usersonline_ipaddress` VARCHAR(25) COLLATE utf8_general_ci DEFAULT NULL UNIQUE,
  PRIMARY KEY (`usersonline_id`),
  UNIQUE KEY `usersonline_id` (`usersonline_id`),
  KEY `useronline_ipaddress` (`usersonline_ipaddress`))ENGINE=MyISAM;
Continue further with PHP code. Create a new file named usersonline_class.php define class
<?php
	class  usersonline {

           }
?>
In it supplied three variables
.... 
private $session_time; 
private $session_id; 
private $table_name = 'usersonline'; 
... 
Then method setSession
 public function setSessionTime($time){
       
        $this->session_time = $time;
          
     }
With this method, record the current time. Make an checking method to set the time limit a visit.
...
   private function _time_check(){
       
         $time_check = $this->session_time-600;  // 10 minutes
        
         return $time_check;         
     }
...
That will skipped simple methods set / get will focus only on methods which are carried out. Below the Code includes all methods including the test. We switch to the 'main method' get_nummber_of_visitors Check whether the visitor is already registered if it is not the record if only restore data to the existing visitor. Then, calculating how many visitors should remove the limit on expired visit and return result only records that are registered to 10 minutes.
 public function get_nummber_of_visitors() {
     
        if ($this->_check_visitor($this->session_id)=== false) {
            $this->_insert_visitor($this->session_id);
        } else {
            $this->_update_registered($this->session_id);       
        }        

		$users_on = $this->_get_all();
        $this->_remove_expire_visitors();
        
        return $users_on;    
    }
  
  }
This is a very simple class with the demo here
<?php                                        
    
  class usersonline {
      
      private  $session_time;
      private  $session_id;
      private  $table_name = 'usersonline';
      
     /**
     * Session time in seconds
     *      
     * @param integer $time
     */
     public function setSessionTime($time){
       
        $this->session_time = $time;
          
     }
     
     /**
     * Set session limit...
     * 
     */     
     private function _time_check(){
       
         $time_check = $this->session_time-600;  // 10 minutes
        
         return $time_check;         
     }
     
    /**
    * Set session id...
    * 
    *      
    * @param string $id
    */
    
    public function setSessionID($id) {
        
        $this->session_id = $id;
        
    }
    
    /**
    * check if user is registered by session id
    *   
    * @param string $session_id
    */
    private function _check_visitor($session_id) {
        
        $sql="SELECT * FROM ". $this->table_name. " WHERE `usersonline_session` = '". $session_id. "'";    
        $result=mysql_query($sql);
        $count=mysql_num_rows($result);  
        
        if ($count == 0) {
            return false;
        }  else {
            return true;
        }
    }  
  
    /**
    * update time if user registered by session id...
    * 
    * 
    * @param string $session_id
    */
    private function _update_registered($session_id){
       
     $sql = "UPDATE ". $this->table_name." SET `usersonline_time`='". time(). "WHERE `usersonline_session` ='". $this->session_id. "'";   
     mysql_query($sql);    
    
    }
    
    /**
    * insert new visitor in base by session_id
    * 
    * @param mixed $session_id
    */
    private function _insert_visitor($session_id) {
                                
      $sql = "INSERT INTO ". $this->table_name. " (`usersonline_session`,
            `usersonline_time`, `usersonline_ipaddress`) VALUES ('". $session_id. "','". time(). "',
            '".$_SERVER['REMOTE_ADDR']."')";  
    
      mysql_query($sql);
    }
    
    private function _remove_expire_visitors() {
        
       $sql = "DELETE FROM ". $this->table_name. " WHERE `usersonline_time` <". $this->_time_check();
        mysql_query($sql);
    }
    
    /**
    * calculate
    * 
    */
    private function _get_all() {
        
        $sql = "SELECT * FROM ". $this->table_name . " GROUP BY `usersonline_ipaddress`";
        return mysql_num_rows(mysql_query($sql));
    }
    
    /**
    *  calculate and return number of users
    * 
    */
    public function get_nummber_of_visitors() {
     
        if ($this->_check_visitor($this->session_id)=== false) {
            $this->_insert_visitor($this->session_id);
        } else {
            $this->_update_registered($this->session_id);       
        }        

		$users_on = $this->_get_all();
        $this->_remove_expire_visitors();
        
        return $users_on;    
    }
  
  }
  
?>
demo:
<?php
  session_start();
  include ('usersonline_class.php ');
  $connection = mysql_pconnect('127.0.0.1', 'demouser', 'demopass');
  mysql_select_db('demo');
  
  
  $myusersonline = new usersonline ();
  $myusersonline->setSessionID(session_id());
  echo $myusersonline->get_nummber_of_visitors();  
?>


views 12883
  1. Add New Comment