how many visitors online – PHP tutorial

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
?>
39 Comments
  1. JML says:

    Hey. nice tutorial. What is REMOTE_ADDR?

    Reply
  2. admin says:

    This is the IP adress of the current visitor.

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

    Reply
  3. scripts says:

    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…?

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

    Reply
  5. Lauren says:

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

    Reply
  6. Guest says:

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

    Reply
  7. alfiad says:

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

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

    Reply
  8. admin says:

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

    I’ve added it to the tutorials

    Cheers

    Reply
  9. michael says:

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

    Reply
  10. schools says:

    great tool to have

    Reply
  11. jignesh says:

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

    Reply
  12. jignesh says:

    its really very useful

    Reply
  13. Jeremy says:

    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?

    Reply
  14. Lane says:

    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

    Reply
  15. Lane says:

    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?

    Reply
  16. Lane says:

    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?

    Reply
  17. Celebrity says:

    great code.

    Reply
  18. legal says:

    code the planet

    Reply
  19. Cameron says:

    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

    Reply
  20. hangsovann says:

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

    Reply
  21. alex says:

    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

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

    Reply
  23. CooooOOOool

    Reply
  24. Stephen says:

    Thanks for this tutorial.

    Reply
  25. Paul says:

    Thanks for this tutorial. This is what I need. I just changed the mysql functions with the methods of my Connection class. I also added the function for getting the country code of each visitor so that you can group it by country. I also added another field on the table for the country code. I think somebody will need it in the future. Hope it can help. Here’s my code:

    function curl($link) {
    // create a new curl resource
    $ch = curl_init();
    // set URL and other headers
    curl_setopt($ch, CURLOPT_URL, “$link”); // this is the link where we get the source
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // grab html
    $response = curl_exec($ch);

    // close curl resource
    curl_close($ch);
    return $response;

    }

    function get_country_code($ip) {
    $output_curl = $this->curl(“http://api.hostip.info/get_html.php?ip=” . $ip);
    preg_match(“/\(([A-Z]+)\)/”,$output_curl, $data);
    return $data[1];
    }

    Reply
  26. Ai says:

    Dear Sir.
    Good tutorial. Thx so much.

    Reply
  27. Alexwebmaster says:

    Hello webmaster
    I would like to share with you a link to your site
    write me here preonrelt@mail.ru

    Reply
  28. I think

    `lastvisit` varchar(100) NOT NULL,

    should be

    `lastvisit` int(10) NOT NULL,

    and ip field

    `ip` varchar(100) NOT NULL,

    should may be

    `ip` varchar(45) NOT NULL,

    You can save the ip in numbers, too. Use the ip2long() function i PHP or inet_aton() in sql.

    Reply
  29. Abhishek says:

    Nice Guide !!

    Reply
  30. pamela says:

    very nice script thank you!

    Reply
  31. auastyle says:

    Thanks for ur tutorial…… I like all of your article. very useful article…

    for all: if there are some mistake, please search the solution by your self.

    Reply
  32. Wow, what a great tutorial. I used this code on one of my sites and it worked great!

    I couldn’t use the code without leaving you a lovely comment and saying thanks so,

    Thanks :D

    Reply
  33. Excellent read, I simply passed this onto a colleague who had been conducting a little research on that. And the man actually bought me lunch because I found it for him smile So i want to rephrase that: Many thanks lunch!

    Reply
  34. MHD says:

    Thank you very match, it’s help me ..

    Reply
  35. I think that they exist easier ways to have a counter… Too difficult for me!

    Reply
  36. nice work!!

    Reply
  37. But this script does not worked. It give an error.

    Reply
Trackbacks / Pings
Leave a Reply




XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


5 + three =