PHP - SHOW USERS ONLINE
Possibly the most sought after PHP script - and here it is!
For this tutorial you will need a MySQL database, as the stats will be hosted on your own server. Also, this tutorial was written assuming you have
phpMyAdmin (Download it!).
In phpMyAdmin, click on your database then click on
SQL at the top. Type this in the box and click 'Go':
PHP Code:
CREATE TABLE `useronline` (
`timestamp` int(15) NOT NULL default '0',
`ip` varchar(40) NOT NULL default '',
`file` varchar(100) NOT NULL default '',
PRIMARY KEY (`timestamp`),
KEY `ip` (`ip`),
KEY `file` (`file`)
)
Now just copy this code where you want the stats to appear:
PHP Code:
<?
//online
$server = "YOUR HOST"; // usually localhost
$db_user = "USERNAME";
$db_pass = "PASSWORD";
$database = "DATABASE";
$timeoutseconds = 300; // length of gaps in the count
//get the time
$timestamp = time();
$timeout = $timestamp-$timeoutseconds;
//connect to database
mysql_connect($server, $db_user, $db_pass);
//insert the values
$insert = mysql_db_query($database, "INSERT INTO useronline VALUES
('$timestamp','$REMOTE_ADDR','$PHP_SELF')");
if(!($insert)) {
print "";
}
//delete values when they leave
$delete = mysql_db_query($database, "DELETE FROM useronline WHERE timestamp<$timeout");
if(!($delete)) {
print "";
}
//grab the results
$result = mysql_db_query($database, "SELECT DISTINCT ip FROM useronline WHERE file='$PHP_SELF'");
if(!($result)) {
print "";
}
//number of rows = the number of people online
$user = mysql_num_rows($result);
if(!($user)) {
print("ERROR: " . mysql_error() . "\n");
}
//spit out the results
mysql_close();
print("$user");
?>
That's it!