I know you always wanted to know who is browsing your website and how many users are online. This one is an easy script, and basically the code is inspired from oscommerce.
Here is the table structure for online users:

I will use PEAR's DB_DataObject/a> as database layer in this tutorial. If you are not familiar with DB_DataObject you can read about it here. I will consider that database connection settings has already been set, as well as dataobject files.
This structure is a simpler one, as you can see we only record Session ID, IP Address, time the user enters your website, last time the user clicked a link on your website.
You could also add some extra information about online users like: what page are they browsing, browser type, where are they coming from, etc.
We want to know who is online in the last 15 minutes. A unique Session ID is generated automatically, and we will store that ID in our database.
Insert or update a user's information into online_users table
- $online_users = DB_DataObject::factory( 'online_users' );
- $nr = $online_users->get('session_id', session_id() );
- $online_users->time_last_click = time();
- $online_users->update();
- }
- else
- {
- $online_users = DB_DataObject::factory( 'online_users' );
- $online_users->time_last_click = time();
- $online_users->time_entry = time();
- $online_users->ip_address = $_SERVER['REMOTE_ADDR'];
- $online_users->insert();
- }
|
The next thing to do is do delete from our table the users that have time_last_click greater than 15 minutes.
- $online_users = DB_DataObject::factory( 'online_users' );
- $online_users->whereAdd("time_last_click < '" . time() - 900 . "'");
- $online_users->delete(DB_DATAOBJECT_WHEREADD_ONLY);
|
These two code snippets should be included in every page of your website.
And the last piece of code, we will list online users:
- $online_users = DB_DataObject::factory( 'online_users' );
- $online_users->orderBy("time_last_click DESC");
- $online_users->find();
- while( $online_users->fetch() )
- {
- echo "IP:" . $online_users->ip_address . " --- Entry time: " . date('H:i:s', $online_users->time_entry ) . '<BR>';
- }
|
|