Page 1 of 1
Usercount
Posted: Sun Sep 21, 2003 4:52 pm
by mlitton
Hi,
How do I count users that are currently visiting my site using PHP?
Could I use sessions and register a specific IP address? How do I remove the from the 'user quota' when they leave the site. Thank you!
-- Mike
Posted: Sun Sep 21, 2003 5:23 pm
by qads
don't need to use sessions, you just a database table with:
ip, timestamp
fields, then insert records in db table with user IP and a time stamp (tim()), use another query to delete old records, how old? thats up to you, i have used from 10sec to 5min at times.
then its matter of simple quesry counting number of rows....
Posted: Sun Sep 21, 2003 6:06 pm
by Nay
Thanks
Posted: Mon Sep 22, 2003 12:26 am
by mlitton
It helped!
Posted: Mon Sep 22, 2003 3:28 am
by qads
always with the easy way eh

Posted: Mon Sep 22, 2003 3:30 am
by Nay
Well, I hope he read through it. I tried some tutorials for that on google but couldn't find a nice one - so I resorted to Wally

.
-Nay
Posted: Tue Sep 23, 2003 5:25 am
by Aaron
Well it doesnt work for me, I edited it further ofcourse and now it always says theres 1 user online when theres more!
Code: Select all
function userdofirst()
{$remote_add = $REMOTE_ADDR;
$tsql = mysql_query("SELECT ip, timeout FROM unz_online where ip = '$remote_add '") or die (mysql_error());
$numrows = mysql_num_rows($tsql);
if ($numrows <= '0')
{$added = mysql_query("INSERT into unz_online (ip, timeout) values ('$remote_add ', '$time')") or die (mysql_error());
if(!$added)
{echo "Insert Error occurred";}}
else
{$usql= mysql_query("UPDATE unz_online SET timeout = '$time' where ip = '$remote_add '")or die (mysql_error());
mysql_query($usql);}}
function usersOnline()
{$seconds = '360';
$tstamp = $time - $seconds;
$result = mysql_query("SELECT ip, timeout FROM unz_online WHERE timeout >= '$tstamp'");
if($result)
{$numrows = mysql_num_rows($result);}
else
$numrows = '0';
if($numrows == '0')
{echo "There are <b>no</b> users online.";}
elseif($numrows <= 1)
{echo "There is <b>" . $numrows . "</b> user online.";}
else
{echo "There are <b>" . $numrows . "</b> users online.";}
$delstamp = time() - $seconds;
// clean up file of outdated ip's
$cqry = mysql_query("DELETE from unz_online where timeout < ".$delstamp."") or die (mysql_error());
$rslt = mysql_query($cqry);}
http://www.wuggawoo.co.uk/sections/forumz/index.php
Posted: Tue Sep 23, 2003 5:43 am
by delorian
Ok, I've written a script, based on that user Nay put here. It's fully operational and in class shell. I've also added some features, like MAX USERS EVER, and some error correction. Sorry for not providing any comments, but I've to erase them casue nobody here could understand them (they were in Polish).
Code: Select all
class whoisonline {
var $rMyConnection;
var $sHost;
var $sUser;
var $sPassword;
var $sDatabase;
var $sTableName;
var $sIP;
var $iInterval;
var $iActualTime;
function whoisonline($sHost,$sUser,$sPassword,$sDatabase,$sTableName,$sIP,$iInterval) {
$this->sHost = $sHost;
$this->sUser = $sUser;
$this->sPassword = $sPassword;
$this->sDatabase = $sDatabase;
$this->sTableName = $this->_validate_name($sTableName);
$this->sIP = $this->_validate_ip($sIP); // IP poddamy walidacji
$this->iInterval = intval($iInterval);
$this->_open_db();
$this->_select_db();
$this->set_max(1);
$this->set_user();
}
function _open_db() {
$this->rMyConnection = @mysql_connect($this->sHost,$this->sUser,$this->sPassword) or die("Nie można połączyć się z bazą danych. ".mysql_error());
}
function _select_db() {
@mysql_select_db($this->sDatabase,$this->rMyConnection) or die("Nie można wybrać bazy danych. ".mysql_error());
}
function _query_db($sQuery) {
$rResult = @mysql_query($sQuery,$this->rMyConnection) or die("Kwerenda nie może być wykonana. ".mysql_error());
return $rResult;
}
function _validate_ip($sIP) {
$sPattern = "/[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}.[\d]{1,3}/";
if(preg_match($sPattern,$sIP)) {
return $sIP;
}
return "127.0.0.1";
}
function _validate_name($sTableName) {
$sPattern = "/[\w\-]+/i";
if(preg_match($sPattern,$sTableName)) {
return $sTableName;
}
return "whoisonline";
}
function set_max($iHowMany) {
$sQuery = "SELECT ip FROM ".$this->sTableName." ORDER BY timestamp DESC LIMIT 1";
$rResult = $this->_query_db($sQuery);
$aMax = @mysql_fetch_assoc($rResult);
if(intval($aMax['ip'])<intval($iHowMany)) {
$sQuery = "UPDATE ".$this->sTableName." SET ip=".intval($iHowMany)." WHERE ip=".intval($aMax['ip']);
$this->_query_db($sQuery);
}
}
function set_user() {
$this->iActualTime = time();
$sQuery = "SELECT * FROM ".$this->sTableName." WHERE ip = '".$this->sIP."'";
$rResult = $this->_query_db($sQuery);
if(!mysql_num_rows($rResult)) {
$sQuery = "INSERT INTO ".$this->sTableName." VALUES ('".$this->sIP."', ".$this->iActualTime.")";
$this->_query_db($sQuery);
} else { // jeśli znalazł to nadpisz jego czas, tak zeby byl aktualny
$sQuery = "UPDATE ".$this->sTableName." SET timestamp = ".$this->iActualTime." WHERE ip = '".$this->sIP."'";
$this->_query_db($sQuery);
}
}
function whois_online() {
$iOverTime = time() - $this->iInterval;
$sQuery = "SELECT COUNT(*) AS users_count FROM ".$this->sTableName." WHERE timestamp >= ".$iOverTime; // -1 dlatego ze jest tam MAX
$rResult = $this->_query_db($sQuery);
$aCount = mysql_fetch_assoc($rResult);
// sprawdzamy czy aby nie bylo teraz wiecej userow niz jest max
$this->set_max($aCount['users_count']-1); // -1 dlatego, że jest tam już jeden wiersz z wartoscia MAX
// kasowanie starych wartosci
$sQuery = "DELETE FROM ".$this->sTableName." WHERE timestamp < ".$iOverTime;
$this->_query_db($sQuery);
return $aCount['users_count']-1; // -1 dlatego, że jest tam już jeden wiersz z wartoscia MAX
}
function max_online() {
// pobieramy aktulany max z tabeli
$sQuery = "SELECT ip FROM ".$this->sTableName." ORDER BY timestamp DESC LIMIT 1";
$rResult = $this->_query_db($sQuery);
$aMax = @mysql_fetch_assoc($rResult);
return $aMax['ip'];
}
}
// and the usage
$sHost = 'localhost';
$sUser = '';
$sPassword = '';
$sDatabase = '';
$sTableName = 'whoisonline';
$sIP = $_SERVER['REMOTE_ADDR'];
$iInterval = 300;
$whoisonline = new whoisonline($sHost,$sUser,$sPassowrd,$sDatabase,$sTableName,$sIP,$iInterval);
echo "USERS ON-LINE: ".$whoisonline->whois_online();
echo "<br>MAX USERS EVER: ".$whoisonline->max_online();
And some SQL
Code: Select all
CREATE TABLE whoisonline (
ip VARCHAR(15),
timestamp INT(10) UNSIGNED
);
-- the 9999999999 here doesn't matter, but it should be the very very large number, larger than 2-3 bilions.
INSERT INTO whoisonline VALUES (0,9999999999);
Posted: Tue Sep 23, 2003 6:25 am
by Nay
delorian wrote:Ok, I've written a script, based on that user Nay put here.....
Hey! lol
Call me Nay
-Nay
Posted: Tue Sep 23, 2003 9:06 am
by delorian
Nay wrote:
Call me Nay
Sorry, Nay.

Posted: Tue Sep 23, 2003 3:05 pm
by Aaron
I dont like classes and I dont need the db bit so I wont try to deciefer your code, if it works Id have like to have used it

Posted: Tue Sep 23, 2003 3:27 pm
by delorian
Aaron wrote:I dont like classes and I dont need the db bit so I wont try to deciefer your code, if it works Id have like to have used it

You don't need to, It is in a class so the only thing you've got to know is how to construct it and what to use to make it work properly.
BTW: Here's an update, because I forgot something usefull and written in good manner

(the close_db() method)
Code: Select all
class whoisonline {
var $rMyConnection;
var $sHost;
var $sUser;
var $sPassword;
var $sDatabase;
var $sTableName;
var $sIP;
var $iInterval;
var $iActualTime;
function whoisonline($sHost,$sUser,$sPassword,$sDatabase,$sTableName,$sIP,$iInterval) {
$this->sHost = $sHost;
$this->sUser = $sUser;
$this->sPassword = $sPassword;
$this->sDatabase = $sDatabase;
$this->sTableName = $this->_validate_name($sTableName);
$this->sIP = $this->_validate_ip($sIP); // IP poddamy walidacji
$this->iInterval = intval($iInterval);
$this->_open_db();
$this->_select_db();
$this->set_max(1);
$this->set_user();
}
function _open_db() {
$this->rMyConnection = @mysql_connect($this->sHost,$this->sUser,$this->sPassword) or die("Nie można połączyć się z bazą danych. ".mysql_error());
}
function _select_db() {
@mysql_select_db($this->sDatabase,$this->rMyConnection) or die("Nie można wybrać bazy danych. ".mysql_error());
}
function _query_db($sQuery) {
$rResult = @mysql_query($sQuery,$this->rMyConnection) or die("Kwerenda nie może być wykonana. ".mysql_error());
return $rResult;
}
function _validate_ip($sIP) {
$sPattern = "/[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}.[\d]{1,3}/";
if(preg_match($sPattern,$sIP)) {
return $sIP;
}
return "127.0.0.1";
}
function _validate_name($sTableName) {
$sPattern = "/[\w\-]+/i";
if(preg_match($sPattern,$sTableName)) {
return $sTableName;
}
return "whoisonline";
}
// THIS IS WHAT I ADD
function close_db() {
@mysql_close($this->rMyConnection) or die(mysql_error());
}
function set_max($iHowMany) {
// END - THIS IS WHAT I ADD
$sQuery = "SELECT ip FROM ".$this->sTableName." ORDER BY timestamp DESC LIMIT 1";
$rResult = $this->_query_db($sQuery);
$aMax = @mysql_fetch_assoc($rResult);
if(intval($aMax['ip'])<intval($iHowMany)) {
$sQuery = "UPDATE ".$this->sTableName." SET ip=".intval($iHowMany)." WHERE ip=".intval($aMax['ip']);
$this->_query_db($sQuery);
}
}
function set_user() {
$this->iActualTime = time();
$sQuery = "SELECT * FROM ".$this->sTableName." WHERE ip = '".$this->sIP."'";
$rResult = $this->_query_db($sQuery);
if(!mysql_num_rows($rResult)) {
$sQuery = "INSERT INTO ".$this->sTableName." VALUES ('".$this->sIP."', ".$this->iActualTime.")";
$this->_query_db($sQuery);
} else { // jeśli znalazł to nadpisz jego czas, tak zeby byl aktualny
$sQuery = "UPDATE ".$this->sTableName." SET timestamp = ".$this->iActualTime." WHERE ip = '".$this->sIP."'";
$this->_query_db($sQuery);
}
}
function whois_online() {
$iOverTime = time() - $this->iInterval;
$sQuery = "SELECT COUNT(*) AS users_count FROM ".$this->sTableName." WHERE timestamp >= ".$iOverTime; // -1 dlatego ze jest tam MAX
$rResult = $this->_query_db($sQuery);
$aCount = mysql_fetch_assoc($rResult);
// sprawdzamy czy aby nie bylo teraz wiecej userow niz jest max
$this->set_max($aCount['users_count']-1); // -1 dlatego, że jest tam już jeden wiersz z wartoscia MAX
// kasowanie starych wartosci
$sQuery = "DELETE FROM ".$this->sTableName." WHERE timestamp < ".$iOverTime;
$this->_query_db($sQuery);
return $aCount['users_count']-1; // -1 dlatego, że jest tam już jeden wiersz z wartoscia MAX
}
function max_online() {
// pobieramy aktulany max z tabeli
$sQuery = "SELECT ip FROM ".$this->sTableName." ORDER BY timestamp DESC LIMIT 1";
$rResult = $this->_query_db($sQuery);
$aMax = @mysql_fetch_assoc($rResult);
return $aMax['ip'];
}
}
// and the usage
$sHost = 'localhost';
$sUser = '';
$sPassword = '';
$sDatabase = '';
$sTableName = 'whoisonline';
$sIP = $_SERVER['REMOTE_ADDR'];
$iInterval = 300;
$whoisonline = new whoisonline($sHost,$sUser,$sPassowrd,$sDatabase,$sTableName,$sIP,$iInterval);
echo "USERS ON-LINE: ".$whoisonline->whois_online();
echo "<br>MAX USERS EVER: ".$whoisonline->max_online();
$whoisonline->close_db();
Posted: Tue Sep 23, 2003 3:35 pm
by Aaron
the db confuses me to hell, can you remove the that for me?
I get confused with classes, they arent called like functions?
Posted: Tue Sep 23, 2003 3:46 pm
by delorian
Aaron wrote:the db confuses me to hell, can you remove the that for me?
Common, the db's aren't such a bad thing as you say. I can't remove them cause you won't get anything from the database
Aaron wrote:
I get confused with classes, they arent called like functions?
Classes aren't called. You make an object which has the properties of class, and then you can call one of the property. So the "problem" with calling class functions (which in fact are methods) is that you have to use the object name before the method and then '->' (pointer) mark
so the typical funciton is called like this:
function_name();
and the object method:
$object->method_name();
BTW: Don't be affraid of classes, they are great after all. And also read:
viewtopic.php?t=8873
Posted: Tue Sep 23, 2003 4:16 pm
by Aaron
Well these functions work well
Code: Select all
function usersonline($uid)
{$ip = $_SERVER["REMOTE_ADDR"];
$time = time();
$timeoutseconds = '300';
$timeout = $time - $timeoutseconds;
$delete = mysql_query("DELETE FROM unz_online WHERE time < '$timeout'");
$insert = mysql_query("INSERT INTO unz_online VALUES ('$time','$ip','$uid')");}
function show_usersonline()
{$check = mysql_num_rows(mysql_query("SELECT DISTINCT ip FROM `unz_online`"));
echo "$check Users online";}
I wish it stored the most visitors ever though XD
Ill read up on classes, but they seem blehish.