This tutorial will show you two different methods to count the users currently surfing your website.
The first method uses a MySQL table to track users, although it can be used with any database supported by PHP with appropriate modification to the scripts. Here is the structure of the table you will need to create within an existing database:
CREATE TABLE `online_users` ( `id` INT( 5 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , `session` VARCHAR( 64 ) NOT NULL , `timestamp` TIMESTAMP NOT NULL , UNIQUE ( `session` ) )
This table has three fields:
- id, a counter that automatically increments for each new user that connects to the site
- session, the unique session ID of each user
- timestamp, the user’s date and time of connection
The PHP code to manage the counting of users is split into two files in order to improve readability.
First is the connection class contained in “Mysql.class.php”:
class Mysql{ public function __construct($host='', $user='', $password='', $db=''){ $this->conn = mysql_connect($host, $user, $password); if ($this->conn) mysql_select_db($db, $this->conn); } public function __destruct(){ if ($this->conn) mysql_close($this->conn); } public function query($sql){ if ($this->conn) return mysql_query($sql); } public function get_connection(){ return $this->conn; } }
This class has a constructor in which connects to the MySQL database, and a destructor that automatically closes the connection at the end of the script. The other two methods are used to execute the queries and to get the MySQL connection that we can use in other functions.
Most of the work will be done by this class in “User.class.php”:
class User{ public function __construct($db, $timer=TIMER){ $this->session = session_id(); $this->db = $db; $this->timer = $timer; } public function update(){ $this->db->query("UPDATE online_users SET online_users.timestamp = CURRENT_TIMESTAMP WHERE online_users.session='". $this->session ."'"); if (mysql_affected_rows($this->db->get_connection()) < 1) $this->db->query("INSERT INTO online_users(session) VALUES ('". $this->session ."')"); $this->db->query("DELETE FROM online_users WHERE online_users.timestamp < CURRENT_TIMESTAMP - INTERVAL ". $this->timer ." SECOND"); } public function count_users(){ $rs = $this->db->query("SELECT COUNT(*) AS users FROM online_users WHERE online_users.timestamp > CURRENT_TIMESTAMP - INTERVAL ". $this->timer ." SECOND"); if ($rs){ $row = mysql_fetch_array($rs); return $row['users']; } else return -1; } }
The constructor’s parameters are the instance of the MySql class from the first file, and the maximum duration (in seconds) for which a user will be considered active. The default duration is specified via a constant called TIMER provided by user code.
The purpose of the update() method is to update or create the record in the MySQL table that corresponds to the current connection, and then to remove all rows older that the duration passed to the constructor.
The count_users() method returns the number of users connected to the site based on when they last connected.
Here is a script that we can use to test the functionality of the code, after changing the parameters passed to the Mysql constructor to appropriate values:
session_start(); define('TIMER', 300); //5 minutes require_once "Mysql.class.php"; require_once "User.class.php"; $db = new Mysql("127.0.0.1", "root", "password", "users"); $user = new User($db); $user->update(); echo $user->count_users();
The second method for counting users does not use MySQL, but instead uses PHP’s session functionality.
This class in “User.class.php” will do all the work:
class User{ public function __construct($timer=TIMER){ $this->timer = $timer; } public function count_users(){ $counter=0; foreach (glob(SESSION_PATH.'/*') as $file){ if(time() - fileatime($file) < $this->timer) $counter++; } return $counter; } }
This script tests the functionality of the class:
define('TIMER', 300); //5 minutes define('SESSION_PATH', '/home/user/session'); session_save_path(SESSION_PATH); session_start(); $user = new User(); echo $user->count_users();
Through use of session_save_path(SESSION_PATH) we set a unique directory for storage of session information in order to prevent conflicts with other PHP applications running on the server.
IMPORTANT: session_save_path() MUST be called before session_start().
After this step we create a new instance of the User class. There is no need for an update() method since we use a quirk of PHP’s session functionality. The count_users() method checks the last access time of the session information files in order to determine how many users are currently connected.
IMPORTANT: On UNIX-like operating systems, this method will NOT work on file systems that are mounted with the noatime mount option.
hi guys…
hi guysI would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well and i have start my own blog now, , thanks for your effort…