Dec 20

Ever wonderd how to display how many visitors you have online. In this tutorial i will show you an easy but effective way to display the amount of online visitor’s.

The database table used by the tutorial

CREATE TABLE `counter` (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `ip` varchar(100) NOT NULL,
  `lastvisit` varchar(100) NOT NULL,
  PRIMARY KEY  (`id`)
);

Next we will be creating a class VisitorCounter:

The variable session time in min is the amount of time has to pass before the script will clear the visitor from the counter.

** The script only clears the visitor if he has not taken any action for sessionTimeInMin amount of time.

<?php
class VisitorCounter {

    var $sessionTimeInMin = 5;
}
?>

Step2: Creating the class contructor

The contructor will clean the database for timed out visitor’s and add/ update visitor’s.

public  function VisitorCounter()
      {
          $ip = $_SERVER['REMOTE_ADDR'];
          $this->cleanVisitors();
 
        if ($this->visitorExists($ip))
          {
              $this->updateVisitor($ip);
          } else
          {
              $this->addVisitor($ip);
          }
      }

Step 3: Creating the cleanVisitors() function:

This function will clear all visitor’s from the database that were inactive for x amount of time.

private  function cleanVisitors()
      {
         
          $sql = "select * from counter";
          $res = mysql_query($sql);
          while ($row = mysql_fetch_array($res))
          {
              if (time() - $row['lastvisit'] >= $this->sessionTimeInMin * 60)
              {
                  $dsql = "delete from counter where id = $row[id]";
                  mysql_query($dsql);
              }
          }
      }

Step4: Creating the visitorExists function:

This function will check if the given visitor is already in the database, if he’s not the function will return false.

public function visitorExists($ip)
    {
        $sql = "select * from counter where ip = '$ip'";
        $res = mysql_query($sql);
        if (mysql_num_rows($res) > 0)
        {
            return true;
        } else
            if (mysql_num_rows($res) == 0)
            {
                return false;
            }
    }

Step5: creating the updateVisitor function:

This function will update the visitor if he’s in the database.

private  function updateVisitor($ip)
    {

        $sql = "update counter set lastvisit = '" . time() . "' where ip = '$ip'";
        mysql_query($sql);
    }

Step6: creating the addVisitor function:

This function will add the visitor if he’s not yet in the database.

private  function addVisitor($ip)
    {
        $sql = "insert into counter (ip ,lastvisit) value('$ip', '" . time() . "')";
        mysql_query($sql);
    }

Step7: getAmountVisitors() function:

This function will return the amount of visitor’s in the database (online at the site).

public  function getAmountVisitors()
    {
        $sql = "select count(id) from counter";
        $res = mysql_query($sql);
        $row = mysql_fetch_row($res);
        return $row[0];
    }

Step8: show() function:

This function will display the actual counter how many online visitors on the webpage.

public function show()
    {
        echo '<div style="padding:5px; margin:auto; background-color:#fff"><b>' .
            $this->getAmountVisitors() . 'visitors online</b></div>';
    }

file: class.visitorcounter.inc.php

The complete how many visitor’s class:

<?php
class VisitorCounter
{
    var $sessionTimeInMin = 5; // time session will live, in minutes
   
  public  function VisitorCounter()
    {
        $ip = $_SERVER['REMOTE_ADDR'];
        $this->cleanVisitors();

        if ($this->visitorExists($ip))
        {
            $this->updateVisitor($ip);
        } else
        {
            $this->addVisitor($ip);
        }


    }

   public function visitorExists($ip)
    {
        $sql = "select * from counter where ip = '$ip'";
        $res = mysql_query($sql);
        if (mysql_num_rows($res) > 0)
        {
            return true;
        } else
            if (mysql_num_rows($res) == 0)
            {
                return false;
            }
    }

  private  function cleanVisitors()
    {
        $sessionTime = 30;
        $sql = "select * from counter";
        $res = mysql_query($sql);
        while ($row = mysql_fetch_array($res))
        {
            if (time() - $row['lastvisit'] >= $this->sessionTimeInMin * 60)
            {
                $dsql = "delete from counter where id = $row[id]";
                mysql_query($dsql);
            }
        }
    }


  private  function updateVisitor($ip)
    {

        $sql = "update counter set lastvisit = '" . time() . "' where ip = '$ip'";
        mysql_query($sql);
    }


  private  function addVisitor($ip)
    {
        $sql = "insert into counter (ip ,lastvisit) value('$ip', '" . time() . "')";
        mysql_query($sql);
    }

  public  function getAmountVisitors()
    {

        $sql = "select count(id) from counter";
        $res = mysql_query($sql);
        $row = mysql_fetch_row($res);
        return $row[0];
    }


   public function show()
    {

        echo '<div style="padding:5px; margin:auto; background-color:#fff"><b>' .
            $this->getAmountVisitors() . 'visitors online</b></div>';

    }

}
?>

Impleting the how many visitor’s counter on your website:

Now we can easily add this counter to our website using only 3 lines of code.

** Don’t forget to include the connection to the database !!

file: dbconnect.inc.php

<?php
define("HOST", "localhost");
// Database user
define("DBUSER", "");
// Database password
define("PASS", "");
// Database name
define("DB", "");

############## Make the mysql connection ###########
$conn = mysql_connect(HOST, DBUSER, PASS);
if (!$conn)
{
    // the connection failed so quit the script
    die('Could not connect !<br />Please contact the site\'s administrator.');
}
$db = mysql_select_db(DB);
if (!$db)
{
    // cannot connect to the database so quit the script
    die('Could not connect to database !<br />Please contact the site\'s administrator.');
}
?>

Now let’s include the visitor counter into the mainpage:

file: index.php

<?php
 require "dbconnect.inc.php"; // db connection
 require "class.visitorcounter.inc.php"; // the counter class itself
 $counter = new VisitorCounter; // make a new counter
//content here
$counter->show(); // show the counter
// and here
?>

Related Posts

  1. JML Said,

    Hey. nice tutorial. What is REMOTE_ADDR?

  2. admin Said,

    This is the IP adress of the current visitor.

    So if you would be viewing that page, it would be your IP adress.

  3. scripts Said,

    how do i make it so that i can get that i can include the # of registered members and the # of admins in the stats script…?

  4. bob Said,

    WlWAYX hi great site thx http://peace.com

  5. Salim Sheikh Said,

    I have this error please solve;

    Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in C:\Inetpub\wwwroot\php\SmallPhp\how-many-visitors-online-PHP-tutorial\class.visitorcounter.inc.php on line 71
    visitors online

  6. Lauren Said,

    Hey Salim your getAmountVisitors function is not selecting anything from the database. Make sure your database has a connection file like shown in the tutorial. Also make sure your table name in the databse is right. He has made his table called counter and make sure you’ve written in the right name for the id your selecting in the database. he has called the id column count(id).

    public function getAmountVisitors()
    {
    $sql = “select count(id) from counter”;
    $res = mysql_query($sql);
    $row = mysql_fetch_row($res);
    return $row[0];
    }

  7. Guest Said,

    What do we need to add to database? –..–

  8. alfiad Said,

    i just wanna ask, what server are u using (appserv? vertrigoserv?)?

    pls send your reply to my
    e-mail add.. afterdeath_2k4@yahoo.com

  9. admin Said,

    it seems by mistake the SQL declaration of the table was not included in the tutorial

    I’ve added it to the tutorials

    Cheers

  10. bob Said,

    eOXrbC hi nice site man thx http://peace.com

  11. michael Said,

    I was only able to upload the tables.
    Those codes…
    Where do i paste them to??/
    Thanks

  12. schools Said,

    great tool to have

  13. jignesh Said,

    It is very important for know how many visitor r on line.

  14. jignesh Said,

    its really very useful

  15. bob Said,

    cqCTWp hi nice site thx http://peace.com

  16. barbara Said,

    auIKnQ g84nst394kldshg641h0

  17. Lane Said,

    were do i put all these codes, lol
    public function VisitorCounter()
    {
    $ip = $_SERVER[’REMOTE_ADDR’];
    $this->cleanVisitors();

    if ($this->visitorExists($ip))
    {
    $this->updateVisitor($ip);
    } else
    {
    $this->addVisitor($ip);
    }
    }

    and do i place them inside the and do they go on the websirte or what XD

  18. Lane Said,

    im curiouse to know, if someone is on the website, but it minimized the website, does it still count them on if there are away and minimized the site for more than an hour?

  19. Lane Said,

    i got it all figured out, now what i need to know is how can i edit a page so that after useing it on a page i want a totally different website to see my websites hits w/o counting the other website people, just so the other website can see how many current users are exactly on my website, any ideas asmin or php coders?

  20. Celebrity Said,

    great code.

  21. legal Said,

    code the planet

  22. hangsovann Said,

    Dear sir

    i got some mistake, please help me:

    when i run it on my local machine it is good
    but i upload it to the server it not show the number of visitors.

    How can i do? please help !!!

  23. WasiL Said,

    : : : : : : :
    : : : : : : :
    : : GreaT : :
    : : : : : : :
    : : : : : : :
    : Thank you :
    : : : : : : :
    : From: wasiL

Add A Comment