All in one forum  - Applications | Games | E-Books | Music, Movies & Videos | Mobile Stuff | Live Discussions | Webmaster Stuff | Many More | Community to Hang Out & Stick to
Mark Forums Read

Go Back   Home > Tutorial Section > Programming > PHP
Reload this Page [Tutorial] Online user counter - PHP
Forgot Password? Join Us!
PHP Post your Personal Home Pages Programing Tutorial Here

Notices
Free Image Hosting Solution for all Your link here @ 10$ 10 K Unique Visitors 1 Million Visitors Per Month Your link here @ 10$

Your Ad Here

Rate This Thread - Online user counter - PHP.

Post New Thread Reply
 
LinkBack Thread Tools Display Modes
  (#1 (permalink)) Old
 
KoOL's Avatar
 
User Info
Join Date: Oct 2007
Location: In You Mind
Age: 27
Achievements Posts: 10,866
Casino Cash: $1145930

Total Points: 237,966,478,269.57
Donate

KoOL has disabled reputation

Awards Showcase
Administrator Of the Month Of Jan 
Total Awards: 1
Online user counter - PHP - 06-13-2008, 05:29 AM

One of the primary aims of most people with the responsibility of maintaining a web site is to promote it in order to attract as many visitors to the site as possible. There are plenty of techniques and methods for doing this but that's not what this tutorial is about. Instead, this tutorial will teach you how you can create your own user counter which will allow you to see how many people are currently on your web site. This is a piece thing to know if you are interested in just how many people use your site at any given time.
Quote:
Table of contents
Quote:

  1. The idea
  2. Set up the database
  3. The main code
  4. Implementing it
1. The idea

Okay, so what exactly are we going to be doing here? Well the aim is to be able to count how many users are currently on your web site so in order for us to do this we need to be tracking them somehow. By using a MySQL database and just a single table we can do exactly that.

For this to work you will need access to a MySQL database - if you do not have this then you should contact your host and find out if they can provide this for you.
2. Set up the database

Once you've got your database created and ready (whether you or your host does it) it's now time to get to work on our table. Before creating any tables you should ask yourself exactly what data you need it to store. In the case of this script you will need to store just two things: the visitors IP address and the time they last visited.

In order to create this table you can either do it manually using the table creation section of phpMyAdmin or alternatively you can just run the following SQL query on your database.
CREATE TABLE `user_online`
(
`ipaddress` VARCHAR( 15 ) NOT NULL,
`lastactive` INT( 10 ) NOT NULL,
PRIMARY KEY ( `ipaddress` )
)

The above query will create a table called "user_online" which has two columns - ipaddress and lastactive. The ipaddress column has been give the VARCHAR data type which means it accepts a string of all characters of up to 15 in length. This is needed because a typical IP address in the form of xxx.xxx.xxx.xxx is 15 characters long. The lastactive colum has been given the INT data type which basically means it can accept integers with a maximum length of 10.

Now that we have created our table now is a good time to take note of a few things. Firstly you will need to know the name of your database - for this tutorial mine is called "mydatabase" but yours will most likely be different. You will also then need the username and password for that database. These are needed so that our PHP script can connect to the MySQL database. And then finally you will need to know your server name but this isn't vital - usually you can substitute it with "localhost" and it should work just fine.
3. The main code

Now that the database is ready we can now start looking at the PHP code which will make up our user tracking script. Take a look at the following piece of code which should be saved as "online.php" or something similar.
// Database connection and selection
mysql_connect("localhost", "root", "") or die("Cannot connect");
mysql_select_db("mydatabase") or die("Cannot select database");

// Query for the visitors IP address
$ipQuery = mysql_query("SELECT * FROM user_online WHERE ipaddress = '" . $_SERVER['REMOTE_ADDR'] . "' LIMIT 1");

// Have they visited before?
if(mysql_num_rows($ipQuery) == 1)
{
// They have visited before
// Update last active time
mysql_query("UPDATE user_online SET lastactive = " . time() . " WHERE ipaddress = '" . $_SERVER['REMOTE_ADDR'] . "' LIMIT 1");
}
else
{
// They have not visited before
// Insert new row
mysql_query("INSERT INTO `user_online` VALUES ('" . $_SERVER['REMOTE_ADDR'] . "', " . time() . ")") or die(mysql_error());
}

// Delete any old records (where lastactive < NOW - 5 Mins)
mysql_query("DELETE FROM user_online WHERE lastactive < " . (time() - 300)) or die(mysql_error());

// Query all views
$allViewQuery = mysql_query("SELECT * FROM user_online");

// Get the row count
$onlineCount = mysql_num_rows($allViewQuery);

echo "There is currently " . $onlineCount . " user(s) online";

The above code is our entire user tracking script. Now let me take you through it.

In line number 2 we use the mysql_connect() function. This function allows PHP to connect to the MySQL server so that it can then access its databases. This function requires three parameters which are the servers address (although "localhost" usually does the trick), the servers username (in this case "root") and the servers password (in this example it's been left blank). All three of these details can be obtained by speaking to your host.

We then on line 3 have the mysql_select_db() function. Similarly to mysql_connect(), this function is required if you wish your script to connect to a MySQL database. Where the previous function connects to the server this function takes care of selecting which database to use. It requires only one parameter (although you can provide others for slightly more advanced use) which is the name of the database which you would like to connect to (my database is called "mydatabase"). Again if you are unsure of the names or if you do not even have access to any MySQL databases get in touch with your host.

Now that our script has connected to the database we can now start working on the main section of our script. Now the logic behind this script can be explained like this.
Has the user visited before?
> If yes
Update users last active time in database
> If no
Insert new users details into database

Remove any old records which are now unnecessary

Output number of online users

So as you can see the first thing to do (apart from connecting to the database) is to use an if statement to determine if the person visiting is new or if they have visited before. This is done by querying our table using an SQL query and the mysql_query() and pull all rows where the ipaddress column is equal to the current users IP address. If a row exists then we need to do another query to update that rows lastactive column. If however no rows are returned then we need to insert the current visitors IP address and the time into the table as a new row.

Our initial query and the if-else statement is as follows.
$ipQuery = mysql_query("SELECT * FROM user_online WHERE ipaddress = '" . $_SERVER['REMOTE_ADDR'] . "' LIMIT 1");

// Have they visited before?
if(mysql_num_rows($ipQuery) == 1)
{
// They have visited before
// Update last active time
mysql_query("UPDATE user_online SET lastactive = " . time() . " WHERE ipaddress = '" . $_SERVER['REMOTE_ADDR'] . "' LIMIT 1");
}
else
{
// They have not visited before
// Insert new row
mysql_query("INSERT INTO `user_online` VALUES ('" . $_SERVER['REMOTE_ADDR'] . "', " . time() . ")") or die(mysql_error());
}

In the code above we have used the mysql_num_rows() function - this function counts the number of rows which the supplied query returned which we can then use in our if-else statement. That's the 'tracking' part over and done with.

We could just go straight ahead and count all the rows in the table to determine how many people have visited - but that wouldn't necessarily show how many are actually on our site. To do this we need to remove any rows which are too old (more than 5 minutes old). To do this we simply perform another query on our user_online table and delete all rows where the lastactive column < NOW - 300. The number 300 is used because there are 300 seconds in 5 minutes. This is done in this line.
mysql_query("DELETE FROM user_online WHERE lastactive < " . (time() - 300)) or die(mysql_error());

Brilliant. Now we can move on and find out how many people have visited our script in the last 5 minutes, which is probably the easiest way to determine how many people are currently on your site.

To do this we do a simple query and pull all rows from our table. The number of rows returned equals the number of users online.
// Query all views
$allViewQuery = mysql_query("SELECT * FROM user_online");

// Get the row count
$onlineCount = mysql_num_rows($allViewQuery);

echo "There is currently " . $onlineCount . " user(s) online";

4. Implementing it

As far as our tracking script goes we're all done. All that's left to do is to implement it into your web site so you can see how many users are currently online.

There are two possible ways of doing this. Firstly we could use the PHP include() function and include our online.php script into all of our PHP enabled web pages. This can be done with just one line like this.
include('online.php');

Alternatively, if your web page is not PHP enabled then you can include it using an iframe. This can be done by using the following HTML code.
<iframe src="online.php"></iframe>

That's it - you should now be able to keep a track on how many people are currently on your site. Enjoy!



For Download Links U need to Press Thanks Button

Please don't PM me For Posts, Request and Not Working Threads. Use Button.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
The Following 2 Users Say Thank You to KoOL For This Useful Post:
barnick (06-28-2008), mikedhani (08-16-2008)
Click here to Donate to remove the Adverts.
Your Ad Here
  (#2 (permalink)) Old
 
User Info
Join Date: Dec 2007
Achievements Posts: 36
Casino Cash: $4700

Total Points: 842.15
Donate

Reputation: 40
mikedhani is on a distinguished road


07-02-2008, 01:55 AM

Thanks again ....
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Click here to Donate to remove the Adverts.
Your Ad Here
Post New Thread Reply

Bookmarks


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Counter Terrorist Teams hacks TV Zone 1 06-13-2008 09:57 AM
Counter Strike : SOURCE (Works Online) star01 PC Games 9 06-03-2008 02:59 PM
[HTTP] Counter Strike Source + WORKS ONLINE + newest updates hackproof Garbage Bin 3 05-21-2008 04:16 PM
Counter Strike 1.6 - Setup? titleist5151 Local Area Networking 0 07-26-2007 09:47 PM
Counter Strike 1.6 Zoe PC Games 0 07-16-2007 04:54 PM


New To AiO Forum? Need Help?

All times are GMT. The time now is 12:25 AM.
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
vBulletin Skin developed by: vBStyles

RapidShare Links PhazeDDL Warez
PhazeDDL Warez