Over a million developers have joined DZone.

Creating a Users Online Script using PHP

DZone's Guide to

Creating a Users Online Script using PHP

· Web Dev Zone ·
Free Resource

Building real-time chat? Enroll in a Free Course on Mobile Chat Development. 

Creating a way to show how many users are currently visiting your website has become a fad amongst webmasters. It's a cool way to show off your skills has a coder and to show your visitors how many other people are looking at the same thing they are. You don't want to miss the bandwagon again do you? This script is also an excuse to brush up on some mildly advanced MySQL queries.

The first thing to understand is that this sort of script is never 100% accurate. The way this works is when a user visits your site their IP along with a timestamp is inserted into a table. The coder specifies a timeout period in which they assume the user will spend that amount of time on a single page. After the timeout period has elapsed it is safe to say they have left our website.

CREATE TABLE `usersonline` (  
 `ip` VARCHAR( 20 ) NOT NULL ,  
 `time` INT NOT NULL  

So, let's get started. The first thing to do is to set up our table. In this simple demonstration 3 fields should do just fine. 

 id - Our primary key. Every good table needs an id field.
 ip - The IP of our visitor.
 time - A unix timestamp of when our visitor was last seen.

Now the function:

    function usersonline() {  
      // Time in seconds that user is assumed to visit site  
      $timeout = 300;  
      // Insert users ip into table  
      mysql_query("INSERT INTO usersonline  
                 ") or die(mysql_error());  
      // Delete timed out records in table  
      $deadline = time() - $timeout;  
      mysql_query("DELETE FROM usersonline WHERE time < '".$deadline."'") or die(mysql_error());  
      // Query table for distinct IP's and return result  
      $result = mysql_query("SELECT DISTINCT ip FROM usersonline") or die(mysql_error());  
      return mysql_num_rows($result);  

That should do it. As you can see I've set this up as a function so it can be called from anywhere. The first chunk of code sets the timeout variable to the number of seconds we assume a visitor will view a single page without moving on. After this time has elapsed we assume the user has left the site.

The following Query inserts our users information into the table. You may have noticed I used MySQL's UNIX_TIMESTAMP() function. This is identical to PHP's time() function and it makes the code look cleaner without extra quotes and periods.

The deadline variable is going to be used in the following delete query to help tell which values to delete from the table. Here is an example using SIMPLE timestamp values.

Let's say a users last visited at timestamp: 1000 and our script is triggered again at 1500. 

$deadline will be set to the current time minus our timeout period so: $deadline = 1500 - 300 = 1200

Now the delete query will run and will delete any records where the time field is less than 1200, effectively showing that any users in that range have left the website.

Now that that is out of the way, it's finally time to tell how many records are left in the table thus showing how many users are currently on the site.  The query for this uses DISTINCT ip so that if there are multiple records of the same IP address they will only be counted as one. A good example of this is if a user skimmed a couple pages within in 300 second timeout period. We don't want to count a single user multiple times so that is the reason for having DISTINCT in the query.

Finally we return the number of rows and voila, we have the number of users online.

Extra Reading

Spoono Users Online - A good tutorial that goes beyond what was covered here and includes functionality to show current users for separate pages.

Power realtime chat, IoT and messaging apps at scale. Pubsub realtime messaging, functions, chat, presence, push, notifications, blocks catalog and more.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}