User Authentication With patUser (part 3) - Big Brother Is Watching (
Page 6 of 7 )
patUser also allows you to record statistical information about user
logins via its very cool addStats() and updateStats() methods. There are five
different pieces of data you can store: the user's first login, last login,
total number of logins, total number of pages visited and total time on your
site. The data thus collected is stored in the "users" table as a component of
each user record, and can be viewed using regular SQL queries.
In order
to enable this feature, you need to tell patUser which pieces of data you want
to track by calling addStats()at the top of your PHP scripts, once for each
item. Once that's done, you can update the database with the latest statistics
at any time by calling updateStats(). The following example demonstrates:
<?php
// include classes
include("../include/patDbc.php"); include("../include/patUser.php");
include("../include/patTemplate.php");
// initialize database layer
$db = new patMySqlDbc("localhost", "db211", "us111", "secret");
// initialize template engine
$tmpl = new patTemplate();
$tmpl->setBasedir("../templates");
// initialize patUser
$u = new patUser(true);
// connect patUser to database/template engines
$u->setAuthDbc($db);
$u->setTemplate($tmpl);
// decide which data to save
$u->addStats("last_login");
$u->addStats("count_logins");
$u->addStats("count_pages");
$u->addStats("time_online");
// update statistics
$u->updateStats();
?>
If you're using a single init() function to initialize your
patUser object, the calls to addStats() should probably go into that function,
so that statistics generation is enabled every time patUser starts up. And if
you're not using patUser's default tables, you can have the data saved to your
own custom fields, simply by specifying each field name as the second argument
in your calls to addStats().
These statistics can come in handy for
database administrators to track user logins and gauge site popularity via time
spent online and number of logins; it can also provide an audit trail for
internal usage tracking and monitoring.