Home arrow MySQL arrow Page 3 - Finding How Many Users Are On Your Site With PHP
MYSQL

Finding How Many Users Are On Your Site With PHP


Counting the number of users that are currently browsing your site is a great way to brag about your high number of unique visitors if you're running a busy web site. In this article Joe shows us how to use PHP and a MySQL database to show the common "There are currently 23 users online" text on our web site. He uses two very simple scripts to do this, and the result is small, quick and informative. If you run your own site, then be sure to check this article out!

Author Info:
By: Joe O'Donnell
Rating: 5 stars5 stars5 stars5 stars5 stars / 21
April 27, 2002
TABLE OF CONTENTS:
  1. · Finding How Many Users Are On Your Site With PHP
  2. · Building the database
  3. · Creating the PHP script
  4. · Displaying the number of users
  5. · Conclusion

print this article
SEARCH DEVARTICLES

Finding How Many Users Are On Your Site With PHP - Creating the PHP script
(Page 3 of 5 )

Our simple PHP scripts will do two things: Firstly, they will add new records to the usersOnline table whenever a new user requests a page from our site. Secondly, they will tally up all of the records in the usersOnline table that were added in the last twenty minutes and display that number in the form of "There are 23 users online".

First off, we will create a file that contains the details of our database. Call it dbinfo.php and enter the following code into it:

<?php

$dbServer = "localhost";
$dbName = "siteStats";
$dbUser = "admin";
$dbPass = "password";

?>


In dbinfo.php we just specify the details of our database. You should change $dbUser and $dbPass to match the login details for your MySQL setup.

Next, we want to create the script that will add the users details to our usersOnline table if they haven't requested a page in the last twenty minutes. The script is called adduser.php and looks something like this:

<?php

include("dbinfo.php");

global $HTTP_SERVER_VARS;

// Set length of session to twenty minutes
define("SESSION_LENGTH", 20);

$userIP = $HTTP_SERVER_VARS["REMOTE_ADDR"];

$sConn = @mysql_connect($dbServer, $dbUser, $dbPass)
or die("Couldnt connect to database");

$dbConn = @mysql_select_db($dbName, $sConn)
or die("Couldnt select database $dbName");

$timeMax = time() - (60 * SESSION_LENGTH);
$result = mysql_query("select count(*) from usersOnline where unix_timestamp(dateAdded) >= '$timeMax' and userIP = '$userIP'");

$recordExists = mysql_result($result, 0, 0) > 0 ? true : false;

if(!$recordExists)
{
// Add a record for this user
@mysql_query("insert into usersOnline(userIP) values('$userIP')");
}

?>


If the script looks a little confusing then allow me to run through it. First off, we define the length of a session. A session in this case is the time that a user spends on our site. It's typically timed at 20 minute intervals, so we use define() to create a constant variable with the value of 20 minutes:

// Set length of session to twenty minutes
define("SESSION_LENGTH", 20);


To tell which users are visiting our site, we then grab their IP from the $HTTP_SERVER_VARS array, which contains details of all important server related variables, such as the document root, server type, etc:

$userIP = $HTTP_SERVER_VARS["REMOTE_ADDR"];

It's now time to connect to the database. At the top of our script we include dbinfo.php, which we created earlier. We use mysql_connect and mysql_select_db to get a connect to our siteStats database:

$sConn = @mysql_connect($dbServer, $dbUser, $dbPass)
or die("Couldnt connect to database");

$dbConn = @mysql_select_db($dbName, $sConn)
or die("Couldnt select database $dbName");


If any errors occur when trying to connect to the database, they are not displayed because we used the @ symbol prepended to the function calls. Instead, the die() function will be called, outputting a simple error and then ending the script.

Once connected to our database, we need a way to workout if the current user has already visited any page on our site within the last twenty minutes (or whatever you define SESSION_LENGTH to be). We do this by comparing the dateAdded field with the systems timestamp, which we get from a call to time():

$timeMax = time() - (60 * SESSION_LENGTH);

In our script, $timeMax will now contain a timestamp that represents the current time minus SESSION_LENGTH minutes. With the $timeMax variable ready to go, we now query our MySQL database using MySQL's UNIX_TIMESTAMP function to return our dateAdded field as a Unix timestamp:

$result = mysql_query("select count(*) from usersOnline where unix_timestamp(dateAdded) >= '$timeMax' and userIP = '$userIP'");

The next line may look a bit tricky but it's really not. We're grabbing the number of records returned from our SQL query with mysql_result and if there’s at least one record, then $recordExists is set to true. If not, it's set to false:

$recordExists = mysql_result($result, 0, 0) > 0 ? true : false;

The ? : syntax that I've used in the line above is common in C-type languages such as C, C++ and PHP. It's a comparative operator, and is really just a short hand version of an if statement:

If (condition)
Do action
Else
Do another action

For example, we could use If statements like this:

If ($x == 5)
$y = 1;
else
$y = 0;


Or, we could use the ? : syntax to do the same thing but with just online line of code, like this:

$y = ($x == 5 ? 1 : 0);

Anyhow, back to our code. The last thing we need to do is add a record for this user if one wasn't found (i.e. $recordExists = false). We do this with a simple INSERT INTO query:

if(!$recordExists)
{
// Add a record for this user
@mysql_query("insert into usersOnline(userIP) values('$userIP')");
}


And that's all there is to our adduser.php script! Now that we can get users into the database, it's extremely easy to show "There are xxx users online".
blog comments powered by Disqus
MYSQL ARTICLES

- MySQL and BLOBs
- Two Lessons in ASP and MySQL
- Lord Of The Strings Part 2
- Lord Of The Strings Part 1
- Importing Data into MySQL with Navicat
- Building a Sustainable Web Site
- Creating An Online Photo Album with PHP and ...
- Creating An Online Photo Album with PHP and ...
- PhpED 3.2 – More Features Than You Can Poke ...
- Creating An Online Photo Album with PHP and ...
- Creating An Online Photo Album with PHP and ...
- Security and Sessions in PHP
- Setup Your Personal Reminder System Using PHP
- Create a IP-Country Database Using PERL and ...
- Developing a Dynamic Document Search in PHP ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials