how many visitors online – PHP tutorial
Written by Gertjan on December 20th, 2007Ever 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: counter, how many visitors online, online counter, PHP, tutorial, visitors online
Related Posts:
January 8th, 2008 at 10:17 PM
Hey. nice tutorial. What is REMOTE_ADDR?
January 9th, 2008 at 12:13 AM
This is the IP adress of the current visitor.
So if you would be viewing that page, it would be your IP adress.
January 17th, 2008 at 5:03 PM
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…?
February 15th, 2008 at 5:15 AM
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
February 24th, 2008 at 10:19 PM
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];
}
February 26th, 2008 at 4:28 AM
What do we need to add to database? –..–
February 28th, 2008 at 6:27 PM
i just wanna ask, what server are u using (appserv? vertrigoserv?)?
pls send your reply to my
e-mail add.. afterdeath_2k4@yahoo.com
February 28th, 2008 at 7:21 PM
it seems by mistake the SQL declaration of the table was not included in the tutorial
I’ve added it to the tutorials
Cheers
April 8th, 2008 at 9:31 PM
I was only able to upload the tables.
Those codes…
Where do i paste them to??/
Thanks
April 25th, 2008 at 7:00 PM
great tool to have
May 3rd, 2008 at 7:49 AM
It is very important for know how many visitor r on line.
May 3rd, 2008 at 7:50 AM
its really very useful
May 11th, 2008 at 3:54 AM
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?
June 4th, 2008 at 4:24 AM
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
June 6th, 2008 at 5:09 AM
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?
June 9th, 2008 at 2:33 AM
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?
June 12th, 2008 at 11:37 PM
great code.
June 18th, 2008 at 6:13 PM
code the planet
June 20th, 2008 at 1:42 PM
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
June 25th, 2008 at 11:16 AM
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 !!!
September 28th, 2008 at 5:37 PM
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
November 10th, 2008 at 9:32 PM
plz, help me by telling how can i know how many visitors my website get everyday ?
November 15th, 2008 at 5:32 PM
CooooOOOool
November 26th, 2008 at 4:13 AM
Thanks for this tutorial.
January 17th, 2009 at 7:15 AM
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];
}
February 20th, 2009 at 7:35 PM
[...] 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, [...]
March 3rd, 2009 at 4:18 AM
Dear Sir.
Good tutorial. Thx so much.
March 3rd, 2009 at 9:03 AM
Hello webmaster
I would like to share with you a link to your site
write me here preonrelt@mail.ru
March 11th, 2009 at 5:31 PM
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.
May 13th, 2009 at 10:40 AM
Nice Guide !!
May 22nd, 2009 at 3:18 PM
news
June 5th, 2009 at 3:07 AM
[...] 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. [...]
March 14th, 2010 at 1:36 AM
very nice script thank you!
May 31st, 2010 at 11:09 PM
thnx for this very nice add…
October 20th, 2010 at 11:29 AM
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.
November 27th, 2010 at 10:40 PM
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
April 9th, 2011 at 11:17 AM
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!
June 30th, 2011 at 8:58 AM
Thank you very match, it’s help me ..
October 27th, 2011 at 11:32 AM
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!
November 9th, 2011 at 8:08 AM
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.