Users online with sessions?
Posted: Wed Jul 31, 2002 5:59 am
I'm a big fan of the old Users Online script (which I initially got from Evil Walrus, but which I've seen elsewhere). However as I've seen some users visit the site and their I.P. address has changed from page to page surely a Users Online script with sessions would be both more accurate and also provide more information?
So here is my suggestion, starting with the MySql set-up:
New fields here are pageview (so it can work like a counter), sessionid (self-explanatory) and count (so you can see how many pages a visitor has seen while they've been on the site, surely a good way to see how long people stick around for?).
The script should work like this (forgive me if I've not got the cookie part right, I'm just beginning to learn them... er, much like sessions really):
Am I on the right track?
So here is my suggestion, starting with the MySql set-up:
Code: Select all
CREATE TABLE useronline (
pageview int(15) DEFAULT '0' NOT NULL auto_increment,
sessionid varchar(100) NOT NULL,
count int(15) DEFAULT '0' NOT NULL,
timestamp int(15) DEFAULT '0' NOT NULL,
ip varchar(40) NOT NULL,
file varchar(100) NOT NULL,
PRIMARY KEY (pageview),
KEY ip (ip),
KEY file (file)
);The script should work like this (forgive me if I've not got the cookie part right, I'm just beginning to learn them... er, much like sessions really):
Code: Select all
<?php
// seed with microseconds
function make_seed() {
list($usec, $sec) = explode(’ ’, microtime());
return (float) $sec + ((float) $usec * 100000);
}
srand(make_seed());
$randval = rand(1, 99999);
// delete following line after testing
echo $randval;
session_start();
session_register('sessionid', 'sessioncount');
$sessionid = time();
$sessionid = $sessionid + $randval
$sessioncountїcount]++;
setcookie ("Sitevisitor", $sessionid, time()+14400, "/", ".domain.com");
$server = "xxx";
$db_user = "xxx";
$db_pass = "xxx";
$database = "xxx";
$db = mysql_connect($server, $db_user,$db_pass);
mysql_select_db($database,$db);
$timeoutseconds = 300; //5 minutes
$timestamp = time();
$timeout = $timestamp-$timeoutseconds;
$insert = mysql_query("INSERT INTO useronline VALUES ('0','$sessionid','$sessioncount','$timestamp','$REMOTE_ADDR','$PHP_SELF')",$db);
if(!($insert)) {
print "Useronline Insert Failed > ";
}
$delete = mysql_query("DELETE FROM useronline WHERE timestamp<$timeout",$db);
if(!($delete)) {
print "Useronline Delete Failed > ";
}
$result = mysql_query("SELECT DISTINCT sessionid FROM useronline",$db);
if(!($result)) {
print "Useronline Select Error > ";
}
$user = mysql_num_rows($result);
mysql_close();
if($user == 1) {
print("$user user online\n");
} else {
print("$user users online\n");
}
?>