Here's a common way of doing this:
first you need a database table to store all the current users online:
CREATE TABLE "session" (
"sUser" character varying(50) NOT NULL,
"iTime" integer DEFAULT '0' NOT NULL,
"sIP" character varying(15),
"bGuest" numeric(1,0),
CONSTRAINT pk_session_iID PRIMARY KEY (susername)
);
Then you need to include this function on every page. This will clear any old sessions, and update the data.
function setOnlineUsers(){
$sIP = $_SERVER["REMOTE_ADDR"];
if(session_set()){
$sMemberName = $_SESSION["sMemberName"];
$bGuest = 0;
}
else{
$sMemberName = $sIP;
$bGuest = 1;
}
//Past half hour;
$iTimePast = time()-1800;
$result = mysql_query("DELETE FROM session WHERE iTime < " . $iTimePast);
if(!$result){
trigger_error("Problem removing old Sessions from database", E_USER_ERROR);
return false;
}
$result = mysql_query("SELECT iTime FROM session WHERE sUser ='" . $sMemberName . "'");
if(!$result){
trigger_error("Problem selecting Sessions from database", E_USER_ERROR);
return false;
}
$iTime = time();
if(mysql_numrows($result) == 0)
$result = mysql_query("INSERT INTO session (sUser, iTime, sIP, bGuest) VALUES ('" . $sMemberName . "', '" . $iTime . "', '" . $sIP . "', '" . $bGuest . "')");
else
$result = mysql_query("UPDATE session SET sUser = '" . $sMemberName . "', iTime= '" . $iTime . "', sIP = '" . $sIP . "', bGuest = '" . $bGuest . "' WHERE sUser = '" . $sMemberName . "'");
if(!$result){
trigger_error("Problem creating Session", E_USER_ERROR);
return false;
}
else
return true;
}
I think I misspelled some function names there too lol. You'll have to look them up in the documentation.
Anyway, all that function does is it first clears out all the old sessions (any older then 30 mins).
Then it checks wheter you're logged in or not. If so, it adds or updates the the session table so you're now included in it as a non-guest.
If you're not logged in, you're still added to the session table, but as a guest.
So then you can do queries on this table to see how many people have been on your site in the last 30 mins, including guests and non-guests.
Eg:
function whosOnLine(){
mysql_query("select count(*) from session where bGuest = 0");
list($iMembersOnLine) = mysql_fetchrow();
mysql_query("select count(*) from session where bGuest = 1");
list($iGuestsOnLine) = mysql_fetchrow();
echo "<p>There are currently " . $iGuestsOnLine . " guest(s) and " . $iMembersOnLine . " member(s) online</p>";
if(Session_set())
echo "<p>You are logged in as <br><b>" . $_SESSION["sUserName"] . "</b></p>";
else
echo "<p>You are not logged in. Please login or register to access all parts of the site</p>";
}
Hope that helps.
cya
-Adam 🙂