Number of visitors online system in PHP

Showing the number of visitors online on your website is a very nice feature. For yourself, and also your visitors. In this tutorial you will create a perfect script that does the job.


Welcome to this new Combined Minds tutorial. In this tutorial I will teach you how to create a simple "number of users online" system. This system will be IP based, not session based.

The reason i chose the IP based system, is that some browsers really mess up sessions. This can result in a number thats maybe twice as high as it really is. IP based might not be a perfect technique, for if you have to visitors with the same IP (e.g. a school). It will be stored as one user. But in the end, the IP technique gives a better result than the session technique.

Getting started
First we need a way to store the visitor information. The most fast way is a simple MySQL table, so lets create a new table.

Code:

1
CREATE TABLE c_online (
2
  time bigint(20) NOT NULL default '0',
3
  ip varchar(20) NOT NULL default ''
4
)


In this tutorial i hope i can assume you have basic MySQL knowledge. This code just creates a new table, with 2 fields. One field for storing the time (we'll come back to that later). And one for the IP, so we can keep all visitors apart.

Before we start coding, i will explain you how we're going to create this system. First we'll let the server check if the visitor already has a record in the database. If it doesn't have a record, we'll create a record. And we'll have a new visitor to the website.

If it already has a record, we'll check the time that's stored along with the new visitor. If the time is more then 30 seconds ago, we'll update the time to the current time.

And every time the page is loaded the script deletes all visitors records that are older than 5 minutes/ (300 seconds)

So lets start programming OK? First create your connection with the database.

Code:

1
<?php
2

3
$db
=mysql_connect("localhost","root","pass") or die(mysql_error());
4
mysql_select_db
("test_db",$db);
5

6
?>



OK, simple enough. Lets start with the time. The time is important, we need to know the current time, the time of 30 seconds ago, and the time of 300 seconds ago. All times are made with the time() function. This is a function that uses only seconds, counting from 1970 until now. With this function we can precisely get the times we need for our script.

Also define a variable called $ip, that stores the IP address of the current visitor.

Code:

1
<?php
2

3
$time        
time();
4
$clear_time  
$time 600;
5
$update_time 
$time 30;
6
$ip          
$_SERVER['REMOTE_ADDR'];
7

8
?>



This makes sense. Create 3 time variables containing the current time, 30 seconds ago, and 300 seconds ago. The IP variable also makes enough sense.

Now lets check if this is the first time the visitor opens the website, or if his IP is already stored in the database.

Code:

1
<?php
2

3
$onQuery 
mysql_query("SELECT ip FROM c_online WHERE ip = '".$ip."' LIMIT 1") or die(mysql_error());
4
$onCount 
mysql_num_rows($onQuery);
5

6
?>



Simply checking if IP already exists in the database. If there is a record with the IP, the $onCount variable will contain "1", or else "0".

If the IP is not listed in the table, and so the $onCount variable contains "0", we need to create a new record in the database.

Code:

1
<?php
2

3
if($onCount 1) {
4
    
5
    mysql_query
("INSERT INTO c_online (tijd, ip) VALUES (".$time.", '".$ip."')") or die(mysql_error());
6

7
}
8

9
?>



The $onCount variable is less than 1, so create a new record in the database. Now what if the $onCount variable does contain "1"? OK, lets create the update section, this sections updates the time in the table to the current time, if the table-time is more than 30 seconds old.

Code:

1
<?php
2

3
if($onCount 1) {
4
    
5
    mysql_query
("INSERT INTO c_online (time, ip) VALUES (".$time.", '".$ip."')") or die(mysql_error());
6

7
} else {
8

9
    
// Use the MySQL results of the query we created on the top of the script, this contains the table-time
10
    
$onResults mysql_fetch_assoc($onQuery);
11
    
12
    
// $update_time contains the time of 30 seconds ago, if the table time is older, update the record.
13
    
if($onResults['time'] < $update_time) {
14
        
15
        
// Update time
16
        
mysql_query("UPDATE c_online SET time = ".$time." WHERE ip = '".$ip."' LIMIT 1") or die(mysql_error());
17
    
18
    
}
19

20
}
21

22
?>



I explained all details in the comment, so this should be easy to understand. Now we need to delete all records that contain the time of more then 300 seconds ago. (5 minutes) This is done with one simple query.

Code:

1
<?php
2

3
mysql_query
("DELETE FROM c_online WHERE time < ".$clear_time) or die(mysql_error());
4

5
?>



This means that the table is now 100% up to date, all visitors are listed, and no visitor in the table has a time 5 minutes old. We can now start counting the number of visitors from our table.

Code:

1
<?php
2

3
$coQuery 
mysql_query("SELECT COUNT(ip) FROM c_online") or die(mysql_error());
4
list($coResult) = mysql_fetch_row($coQuery);
5

6
?>



A nice quest that counts the number of different IP addresses in the database. And using list to directly store the MySQL result into the $coResult variable.

Now the only thing left is echoing the result to the screen.

Code:

1
<?php
2

3
if($coResult == 1) {
4
    
5
    
echo '1 visitor online';
6

7
}  else {
8

9
    
echo $coResult.' visitors online.';            
10

11
}
12

13
?>



If there is only 1 person online, we don't need visitors. So we'll keep it apart by using a very simple if statement.

Congratulations, you've just completed a nice script. It would be best to just include this script on the place you want the number of visitors echoed. If you've faced some difficulties, or other comment. Please drop by at our IRC channel.

This is my finished script:

Code:

1
<?php
2

3
$db
=mysql_connect("localhost","root","test") or die(mysql_error());
4
mysql_select_db
("test",$db);
5

6
$time        
time();
7
$clear_time  
$time 600;
8
$update_time 
$time 30;
9
$ip          
$_SERVER['REMOTE_ADDR'];
10

11

12
$onQuery 
mysql_query("SELECT ip FROM c_online WHERE ip = '".$ip."' LIMIT 1") or die(mysql_error());
13
$onCount 
mysql_num_rows($onQuery);
14

15
if($onCount 1) {
16
    
17
    mysql_query
("INSERT INTO c_online (time, ip) VALUES (".$time.", '".$ip."')") or die(mysql_error());
18

19
} else {
20

21
    
// Use the MySQL results of the query we created on the top of the script, this contains the table-time
22
    
$onResults mysql_fetch_assoc($onQuery);
23
    
24
    
// $update_time contains the time of 30 seconds ago, if the table time is older, update the record.
25
    
if($onResults['time'] < $update_time) {
26
        
27
        
// Update time
28
        
mysql_query("UPDATE c_online SET time = ".$time." WHERE ip = '”.$ip.”' LIMIT 1") or die(mysql_error());
29
    
30
    
}
31

32
}
33

34
mysql_query
("DELETE FROM c_online WHERE time < ".$clear_time) or die(mysql_error());
35

36
$coQuery 
mysql_query("SELECT COUNT(ip) FROM c_online") or die(mysql_error());
37
list($coResult) = mysql_fetch_row($coQuery);
38

39
if($coResult == 1) {
40
    
41
    
echo '1 visitor online';
42

43
}  else {
44

45
    
echo $coResult.' visitors online.';            
46

47
}
48

49
?>

Save this tutorial!

Digg! delicious StumbleUpon Furl this Spurl


Page navigation: 1
 By [M]ike on 23-08-2007

Great tutorial. Good job :)




 By Jim on 21-04-2008

Thanks :)



Page navigation: 1

You are not logged in. To reply to this tutorial, please login. If you dont have an account yet, you can register here.

©Copyrights Combined Minds. All rights reserved 2006 - 2009 : Disclaimer