Skip to content
WJunction - Webmaster Forum

Tutorial: Creating a users online script in PHP5

Status
Not open for further replies.
Heya, im a little board at the moment so might as well share some knowledge lol.


This is how you create a Users Online Class in PHP5:

Step 1.
Firstly we need to create a database to hold the information within, the code below would be executed within PhpMyAdmin or what ever MySql Software you are using

Code:
CREATE TABLE IF NOT EXISTS `usersonline` (
	`id` int(10) NOT NULL AUTO_INCREMENT,
	`ip` varchar(15) NOT NULL,
	`location` varchar(512) NOT NULL DEFAULT '/',
	'timestamp` varchar(15) NOT NULL DEFAULT '',	
	UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2231 ;

Step 2.
Ok so lets begin by create the class structure

PHP:
<?php
	class usersonline{
	}
?>

What this has done is basically created an object in witch you can use throught your site. (an object holds several methods and the methods are whats used to do different task.)

Step 3.
Assigning some variables to hold some temporary data

PHP:
<?php
	class usersonline{
		
		var $timeout	= 7200;	//this is the time you want to track  your users back to
		var $ip		= false;	// The ip address of the user
		var $location	= false;	//The location within your site you want to track
		var $time		= false;	//This will just hold the current time
	}
?>

Step 4.
in this step were going to create a function thats know as a constructor, what this means is that when you first initiate the class this function will run to to prepare any data before you actually use the class
PHP:
<?php
	class usersonline{
		
		var $timeout	= 7200;	//this is the time you want to track  your users back to
		var $ip		= false;	// The ip address of the user
		var $location	= false;	//The location within your site you want to track
		var $time		= false;	//This will just hold the current time
	}

	function __construct(){
		//Here we will prepare data
	}
?>

Step 5.
As you can see from the above code we have created a construct method, now we tell the class what to do when its first called

PHP:
<?php
	class usersonline{
		
		var $timeout	= 7200;	//this is the time you want to track  your users back to
		var $ip		= false;	// The ip address of the user
		var $location	= false;	//The location within your site you want to track
		var $time		= false;	//This will just hold the current time
	}

	function __construct(){
		//Here we will prepare data
		$this->time = time();	//$this->time is a reference to var $time..
	}
?>

Step 6.

Ok the class should construct now and what we need to do is to create some methods/functions so we will begin with the function that gets the IP address.

PHP:
<?php
	class usersonline{
		
		var $timeout	= 7200;	//this is the time you want to track  your users back to
		var $ip		= false;	// The ip address of the user
		var $location	= false;	//The location within your site you want to track
		var $time		= false;	//This will just hold the current time
	}

	function __construct(){
		//Here we will prepare data
		$this->time = time();	//$this->time is a reference to var $time..
	}

	public function getIp(){
		$this->ip = $_SERVER['REMOTE_ADDR'];
	}
?>

Ok so when we run the getIp() function this will assign the var $ip with the IP address contained in $_SERVER

Step 7.
here we will create another function that will get the location of the user.

PHP:
<?php
	class usersonline{
		
		var $timeout	= 7200;	//this is the time you want to track  your users back to
		var $ip		= false;	// The ip address of the user
		var $location	= false;	//The location within your site you want to track
		var $time		= false;	//This will just hold the current time
	}

	function __construct(){
		//Here we will prepare data
		$this->time = time();	//$this->time is a reference to var $time..
	}

	public function getIp(){
		$this->ip = $_SERVER['REMOTE_ADDR'];
	}
	
	public function getLocation(){
		$this->location = $_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING'];
		//This should be something like (index.php?page=2)
	}
?>

Step 8.
Ok now we have created all the methods/functions we need for the __constructor we can now update the constructor function

PHP:
<?php
	class usersonline{
		
		var $timeout	= 7200;	//this is the time you want to track  your users back to
		var $ip		= false;	// The ip address of the user
		var $location	= false;	//The location within your site you want to track
		var $time		= false;	//This will just hold the current time
	}

	function __construct(){
		//Here we will prepare data
		$this->time = time();	//$this->time is a reference to var $time..
		//When we run what of the functions it will auto fill the Variables
		$this->getIp();
		$this->getLocation();
	}

	public function getIp(){
		$this->ip = $_SERVER['REMOTE_ADDR'];
	}
	
	public function getLocation(){
		$this->location = $_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING'];
		//This should be something like (index.php?page=2)
	}
?>
Step 9.

Ok no when we instantiate the object it will automatically track the time,ip.location before we run any methods/functions

But below were going to create 2 primary functions that will furfill the main perpose of the script, they are:
  • Update the MySql Table
  • Return the count of users online

Step 9.1

Here were going to update the table with a method

PHP:
<?php
	class usersonline{
		
		var $timeout	= 7200;	//this is the time you want to track  your users back to
		var $ip		= false;	// The ip address of the user
		var $location	= false;	//The location within your site you want to track
		var $time		= false;	//This will just hold the current time
	}

	function __construct(){
		//Here we will prepare data
		$this->time = time();	//$this->time is a reference to var $time..
		//When we run what of the functions it will auto fill the Variables
		$this->getIp();
		$this->getLocation();
	}

	public function getIp(){
		$this->ip = $_SERVER['REMOTE_ADDR'];
	}
	
	public function getLocation(){
		$this->location = $_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING'];
		//This should be something like (index.php?page=2)
	}

	public function update(){
		$time_distance = ($this->timeout - $this->time);
		$sql_query = "DELETE FROM useronline WHERE timestamp < ".$time_distance;
		
		//Ok so now we have an sql string we will run the SQL
		
		mysql_query($sql_query);
	}
?>

Step 9.2

Ok so by now we have update the table and we want to be able to get the LATEST data from mysql witch will tell us how many UNIQUE users we have online

PHP:
<?php
	class usersonline{
		
		var $timeout	= 7200;	//this is the time you want to track  your users back to
		var $ip		= false;	// The ip address of the user
		var $location	= false;	//The location within your site you want to track
		var $time		= false;	//This will just hold the current time
	}

	function __construct(){
		//Here we will prepare data
		$this->time = time();	//$this->time is a reference to var $time..
		//When we run what of the functions it will auto fill the Variables
		$this->getIp();
		$this->getLocation();
	}

	public function getIp(){
		$this->ip = $_SERVER['REMOTE_ADDR'];
	}
	
	public function getLocation(){
		$this->location = $_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING'];
		//This should be something like (index.php?page=2)
	}

	public function update(){
		$time_distance = ($this->timeout - $this->time);
		$sql_query = "DELETE FROM useronline WHERE timestamp < ".$time_distance;
		
		//Ok so now we have an sql string we will run the SQL
		
		mysql_query($sql_query);
	}

	function totalOnline(){
		$count = @mysql_num_rows ( mysql_query("SELECT DISTINCT ip FROM useronline"));
	}
?>

Ok so this function is basicaly calculating how many UNIQUE ip hits have been inserted into the data within the above timeframe.

Step 10
Ok so now the class is finally complete we can safe that into a php file now and name it usersonline.class.php and upload it to your server!


Step 11

Ok so now you want to get the count into your files, we will use the index file for example..

Open your index.php file or whatever file your adding this too and add the following block of code

PHP:
<?php

include 'path/to/usersonline.class.php';

/*
	* :: Just a not you must be connected to the database before you call the class methods!!!
*/

//Assuming connected..

$usersonline = new usersonline;	
/*
	* Ok now as we run this line of code what ever
	* was in the __construct will be auto run!
*/

//Ok we need to make sure that we run the update method to clean the amount of users up.

$usersonline->update(); // ok that should of cleaned tho rows up!

//Now we can add this to the out body for HTML
?>
<html>
	<head>
		<title>Uses online by Litewarez!</title>
	</head>
	<body>
		<!-- your usual body here -->
		<div class="usersonline">We have <?php echo $usersonline->totalOnline(); ?></div>
	</body>
</html>

Ok now everything should be finished and i hope you enjoyed the tutorial.

P.S. Stay Warez
 

6 comments

Gee it would really be a shame If I shared my 10 line solution, though I have added more since that adds support for multiple sites.

Anyway nice tutorial, possibly a little bit to complecated for the average user here and I see you love your OOP. Anyway nice, and keep up the good work.
 
yea i can do a users online in that aswell i just tried to build it with all the very basic OOP factors for the users too learn.. if they dont know it the only way there going to learn is by attempting the things they do not know !
 
I suppose you can look at it that way.

Just thought I would make some people cream lol, nah the codes not that sexy yet.

Code:
function users_online(){
    $res = mysql_query('SELECT COUNT(*) FROM users_online WHERE ip='.ip2long($_SERVER['REMOTE_ADDR']));
    $row = mysql_fetch_array($res,MYSQL_NUM);
    if(!$row[0]){
        mysql_query('INSERT INTO users_online VALUES('.ip2long($_SERVER['REMOTE_ADDR']).','.time().')');
    }else{
        mysql_query('UPDATE users_online SET timer='.time().' WHERE ip='.ip2long($_SERVER['REMOTE_ADDR']));
    }
    $res = mysql_query('SELECT * FROM users_online WHERE timer>'.(time()-(60*10)));
    if(!$res){
        return '0';
    }
    return mysql_numrows($res);    
}


you really should ip2long decreases the size of the sql table needed to store the data and means that it can do int comparson compared to string comparison which is much slower.
 
Relevant bump:

Ive been looking for a script like this but thing what I do not get is why this all happens MySQL based? It's very slow and inneficient for managing the users online in a database.
Using sessions / file-based would be so much faster + more efficient.
 
The reason its mysql based is due to the face that its meant to be used with user tracking and login systems... if you add a user id to the tracker table you can do a RIGHT JOIN in sql to check see when that user is online and last ip etc...

helps with users online AND registered users online !


i do this within Litewarez Webmasters to track what webmasters are active in the chat by scanning sql rows with user id and time less that 3 min ago also with the location file as /webmasters/chat.php

this helps in that way

--

:D
thanks for this :D

in 5th line of sql
it should be
PHP:
    `timestamp` varchar(15) NOT NULL DEFAULT '/',

;)

Not really, the reason the location has a default of / is that its a URI and therefore if its not set then we do the default of / witch in location terms means root.

if anything the timestamp should be an `timestamp` interger(15) NOT NULL DEFAULT 0,
 
Status
Not open for further replies.

About the author

L
Active Member · Joined
I am a skilled programmer within PHP,HTML,CSS,MYSQL and also the owner of several websites Programming, Football...
1,367
Messages
1
Reactions
38
Points

Advertise on WJunction

Reach 1000's of webmasters, hosts & affiliates. Banner & sponsored-thread slots available.

Contact us
Back
Top Bottom