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

1
2
3
4
5
6
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.

1
2
3
4
5
6
  <?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.

1
2
3
4
5
6
7
8
9
10
11
12
13
 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
 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.

1
2
3
4
5
6
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.

1
2
3
4
5
 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).

1
2
3
4
5
6
7
 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.

1
2
3
4
5
  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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
 <?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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?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

1
2
3
4
5
6
7
8
<?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
?>
  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. 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

  5. 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];
    }

  6. Guest Said,

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

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

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

  9. michael Said,

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

  10. schools Said,

    great tool to have

  11. jignesh Said,

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

  12. jignesh Said,

    its really very useful

  13. Jeremy Said,

    Thanks for the good and simple tutorial.

    One question: In the cleanVisitors function, would it be more logical to determine the visitors that require deleting in the query itself, rather than the php code?

    This is simply a question, not a suggestion.
    I don’t know which is more efficient.

    Example 1:
    // I’m not sure if the NOW() function tracks the same type of timestamp, but you get the point
    $sql = “select * from counter where NOW() - lastvisit >= {$this->sessionTimeInMin} * 60″;
    $res = mysql_query($sql);
    while ($row = mysql_fetch_array($res))
    {
    $dsql = “delete from counter where id = $row[id]“;
    mysql_query($dsql);
    }

    Example 2:
    // As a subquery?
    $sql = “delete from counter where id in
    (select id from counter where NOW() - lastvisit >= {$this->sessionTimeInMin} * 60)”;
    $res = mysql_query($sql);

    Comments?

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

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

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

  17. Celebrity Said,

    great code.

  18. legal Said,

    code the planet

  19. Cameron Said,

    if (time() - $row['lastvisit'] >= $this->sessionTimeInMin * 60)

    rather than if( time() - $row['lastvisit'] you should just do a delete with a where WHERE…
    mysql_query(”DELETE FROM counter WHERE lastvisit sessionTimeInMin*60));

    after you
    define(’TIMENOW’, $_SERVER['REQUEST_TIME']? $_SERVER['REQUEST_TIME'] : time());
    at the beginning of your php file. (php 5.1 has $_SERVER['REQUEST_TIME'] and if its not set, just run time() to get it.

    Also $this->sessionTimeInMin * 60 doing that for every row is also another exmaple of unneeded slowness. Instead, in the constructor have
    $this->sessionTimeInSec = $this->sessionTimeInMin*60;
    better than doing it over and over. But it would be better just to take out the calculator (kcalc if using KDE or if your a windows person calc iirc) and add the value in seconds instead.

    and functions and variables are public by default so your only making this incompatible with php 5 by using the public keyword. Instead, just omit this word.

    And another more important note: mysql_fetch_array() should ALWAYS be given a second argument (usually MYSQL_ASSOC for usability, or MYSQL_NUM for use with list($var, $var2, $etc) = mysql_fetch_array($q, MYSQL_NUM)) otherwise you are getting 2, let me say that in english TWO copies of each value, wasting valuable memory.

    Also I have my own online system (which tracks members as well) and I store their PHPSESSID as well so that different sessions count as a different online user (doesn’t really apply to online members although they could be in the online table twice it will only show them once.

    And I wont lie, the use of OOP here is kind of pointless since it is really just procedural code and would be faster to use functions.

    When doing an ‘online now’ system, it is a very good idea to use datastore (cache). So say do
    $q = mysql_query(”SELECT * FROM online”); // never SELECT * but in this example i will
    while( $f = mysql_fetch_array($q, MYSQL_ASSOC) )
    {
    $online[] = $f;
    }
    mysql_query(”REPLACE INTO datastore (name, value) VALUES (’online’, ‘”. addslashes(serialize($online)) .”‘)”);

    and unserialize it to restore.

    and a good idea to only run the cleanup query (DELETE FROM online WHERE lastactivity<”. TIMENOW-60*min) on random page loads to avoid doing it for every page load wasting valuable CPU time.
    so
    if( !mt_rand(0, 4) ) // only do it 1/4 of the time
    {
    $q = mysql_query(”DELETE….”);
    if( mysql_affected_rows() ) // only if a row was deleted
    {
    // rebuild datastore
    }
    }

    hope this helps somebody and hope you update this tutorial with DELETE FROM … WHERE lastvisit rather than SELECTing then deleting one by one running countless unneeded queries

    come join us in ##php on irc.freenode.net

    Also if my website link doesnt work, try adding :8080

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

  21. alex Said,

    I get this error: Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in /home/look/public_html/class.visitors.php on line 6

    running on php4

  22. overseasfun Said,

    plz, help me by telling how can i know how many visitors my website get everyday ?

  23. Kashif Ahmad Rahi Said,

    CooooOOOool

Add A Comment