First, i will assume that you have a MySQL database, and that you know how to use it.
The very first step you must take is to dump the following data into your database
<?php
CREATE TABLE joined (
ip char(15) NOT NULL,
hl timestamp(14),
PRIMARY KEY (ip)
);
?>
The next step is to go to the PHP document where you wish to display the number of people on your site and add the following code ( it looks like a lot, but it's really not. I just like to comment and keep things spaced out to make things easy )
This code can be placed anywhere on the page (i suggest near the top)
<?php
<?php
// database information
$dbhost="host address";
$dbuser="user name";
$dbpass="password";
$dbname="database name";
// disconnected timeout
$timeout = 60; // in seconds.. you can make it higher or lower.. i suggest keeping it at 1 minute
// this will tell apart the people on your site
$ip=getenv("REMOTE_ADDR");
//connect to database
mysql_connect($dbhost,$dbuser,$dbpass);
// remove old connections so that the number doesn't continue to rise like a counter
$strq = "DELETE FROM joined WHERE hl < now()";
$qry = mysql_db_query($dbname,$strq);
$strq = "SELECT count(*) FROM joined WHERE IP='$ip'";
$qry = mysql_db_query($$dbname,$strq);
while ( $r = @mysql_fetch_array($qry) ) {
$ppl = $r["count(*)"];
}
if ($cpt) {
// checks for reloads, etc..
$strq = "UPDATE joined SET hl=hl + $timeout WHERE ip='$ip'";
} else {
// confirmed user updated into database
$strq = "INSERT INTO joined (ip, hl) VALUES ('$ip', now()+ $timeout)";
}
$qry = mysql_db_query($dbname,$strq);
// display the number of connected people
$strq = "SELECT count(*) FROM joined";
$qry = mysql_db_query($dbname, $strq);
while ( $result = @mysql_fetch_array($qry) ) {
$ppl = $result["count(*)"];
}
?>
?>
Now for the last, and easiest step. Simply add the following lines into your php document where you want the number of connected users to be displayed
<?php
<?php
echo $ppl;
?>
?>
That's the end of the tutorial. This could also be modified into a makeshift hit counter with a few modifications.. As always, fool around with it. Happy coding. |