how many visitors online – PHP tutorial

Written by Gertjan on December 20th, 2007

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

Tags: , , , , ,

Related Posts:

40 Responses to “how many visitors online – PHP tutorial”

  1. JML Says:

    Hey. nice tutorial. What is REMOTE_ADDR?

  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.

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

  4. Salim Sheikh Says:

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

  6. Guest Says:

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

  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

  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

  9. michael Says:

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

  10. schools Says:

    great tool to have

  11. jignesh Says:

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

  12. jignesh Says:

    its really very useful

  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?

  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

  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?

  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?

  17. Celebrity Says:

    great code.

  18. legal Says:

    code the planet

  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

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

  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

  22. overseasfun Says:

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

  23. Kashif Ahmad Rahi Says:

    CooooOOOool

  24. Stephen Says:

    Thanks for this tutorial.

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

  26. how many visitors online - PHP tutorial | ineedtutorials.com - Adsense SEO Says:

    [...] here to read the rest: how many visitors online – PHP tutorial | ineedtutorials.com :copy-to-clipboard, design, function, how-many-visitors-online, php, quote, tutorial, [...]

  27. Ai Says:

    Dear Sir.
    Good tutorial. Thx so much.

  28. Alexwebmaster Says:

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

  29. Erik Groda Says:

    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.

  30. Abhishek Says:

    Nice Guide !!

  31. a7mad sa3ed Says:

    news

  32. How many visitors online - Tutorial Collection Says:

    [...] View Tutorial No Comment var addthis_pub=”izwan00″; BOOKMARK This entry was posted on Friday, June 5th, 2009 at 7:37 am and is filed under Php Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. [...]

  33. pamela Says:

    very nice script thank you!

  34. Κατασκευή ιστοσελίδων Says:

    thnx for this very nice add…

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

  36. Rewards Generator Says:

    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

  37. loan payday loan Says:

    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!

  38. MHD Says:

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

  39. Site Vital is a resource for PHP clone scripts, where all products cost only 19.95$ Says:

    I just like the helpful information you provide for your articles. I will bookmark your weblog and test once more right here regularly. I am reasonably sure I will learn a lot of new stuff right here! Best of luck for the following!

  40. hosting , vps ,domain , free host , ten mien , thiet ke web , web design Says:

    Hello, Neat post. There’s an issue together with your site in web explorer, may test this? IE nonetheless is the marketplace chief and a good component to folks will leave out your fantastic writing because of this problem.

Leave a Reply