MySQL
  Home arrow MySQL arrow Page 3 - Finding How Many Users Are On Your Site Wi...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Moblin 
JMSL Numerical Library 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
MYSQL

Finding How Many Users Are On Your Site With PHP
By: Joe O'Donnell
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 16
    2002-04-27

    Table of Contents:
  • Finding How Many Users Are On Your Site With PHP
  • Building the database
  • Creating the PHP script
  • Displaying the number of users
  • Conclusion

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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".

    More MySQL Articles
    More By Joe O'Donnell


     

    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 ...






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT