Navigation
Poll
Would you be an active poster if Ron's Guide had a message board?


Total Votes: 62
Comments: 18 — View
Past pollsPoll idea?
Rate Ron's Guide
Rate our resource at Bigwebmaster.com
Visitors Online
Learn how to track and display the number of users currently browsing your website. Similar to the users online statistics displayed here on Ron's Guide.

To track the visitors coming to our website, we'll use the online.php file.

Each time a visitor loads the page his or her IP address along with a timestamp will be recorded to our "visitors" array in the online.dat file.
This part is easy. Take a look at the script below for our online.php file:

<?php

// This is the IP address of our visitor
$ip_addr $_SERVER['REMOTE_ADDR'];

// Once again, edit this variable
// to the path of your online.dat file
$file '/path/to/online.dat';

// Get our array from the online.dat file
$online file_get_contents($file);
$online unserialize($online);

// Update the entry for this visitor
$online['visitors'][$ip_addr] = time();

// Write the new data back to our file
$handle fopen($file'w');
fwrite($handleserialize($online));
fclose($handle);

?>

Type the code above into your online.php file and save it. If you run the file, your online.dat file should change. There should now be an entry in the "visitors" array. The key is your IP address, the value is the timestamp when you loaded the page.

The code should be pretty easy to understand. I've commented it to try to give you an idea exactly what's going on.

Lines 11 and 12 grab the current online data from our file and unserialize it so we can work with it. Line 15 is the most important part. This line will update the timestamp for the users browsing your website. You will find out why this is necessary later on.

Because of the way PHP handles arrays, if a new user comes to your website (one that doesn't currenlty have an entry in the visitors array). PHP will automatically create the entry for that user. If the user has been to your website, PHP will simply update the value of that entry.

Now that we have our script adding and updating the visits of our users, we need to deal with "idle" visitors. Because PHP can't execute when a user leaves your website, we'll need to remove idle users ourself.

Continue to the next page to learn how.

« Previous [ 1 2 3 ] Next »
Discuss Tutorial: Visitors Online 3 Comments
Comment by Peter on Mar 15, 2006, 9:26 am
Nice one Ron Smile
Comment by Dexxaboy on Mar 17, 2006, 11:35 pm
*Thumbs up* Smile
Comment by Leokingofthelion on Mar 22, 2006, 1:14 am
I'm using it woth my website! Keep the tutorials coming!Tongue

« Previous [ 1 ] Next »
Post a comment
Sorry, you must be a registered member to post comments.

If you would like to register, you can do so here.
If you already have an account, please login.