|
|
| CURRENT VIEWERS IN PHP |
|
I will in this tutorial show you how to make a script that shows you how many
viewers your site has.
|
Making the script
|
|
In order to at all time know how many viewers that are viewing your site, I choose to
store the IP for the users. I use a table in a MySQL database. I first delete the IP that the
user has, and then all the IPs that have existed more than 2 minutes. At the end I
insert the IP to the user and display the currentviewers. The table have to columns, one
that store when the user last updated the page, 'VisitTime', and one that store the
IP, 'VisitIP'.
|
//connecting to the db
$host = "localhost";
$username = "apron";
$password = "apron123";
$database = "dbHits";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
//get the ip
$domain = getenv("REMOTE_ADDR");
//delete this ip in case it exists
$rs = mysql_query("DELETE FROM tbCurrent WHERE VisitIP LIKE '$domain'");
//get all ips
$rs = mysql_query("SELECT * FROM tbCurrent");
while ($row=mysql_fetch_assoc($rs))
{
//delete those which existed more than 2 minutes.
if( (time() - $row['VisitTime']) > 180)
{
$ip = $row['VisitIP'];
$rs = mysql_query("DELETE FROM tbCurrent WHERE VisitIP LIKE '$ip');
}
}
//insert ip and time to database
$time = time();
$sql = mysql_query("INSERT INTO tbCurrent VALUES ('$time', '$domain' ) ");
//get the currentusers
$currentusers = mysql_num_rows($rs);
//display the current users
echo($currentusers);
//close the db connection
mysql_close($server);
|
|
Category
|
Programming with PHP
|
|
Author
|
Tommy Johannessen
|
|
|
|