DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Kalatravas has posted 29 posts at DZone. View Full User Profile

Detect Online Users With PHP

09.17.2010
| 6073 views |
  • submit to reddit
        // You must have seen on some sites displaying the number of users online, this scripts exactly does that it displays number of users currently browsing your site.

<?php
$server = "xxx";
$db_user = "xxx";
$db_pass = "xxx";
$database = "xxx";

$db = mysql_connect($server, $db_user,$db_pass);
mysql_select_db($database,$db);

$timeoutseconds = 300; //5 minutes

$timestamp = time();
$timeout = $timestamp-$timeoutseconds;

$insert = mysql_query("INSERT INTO useronline VALUES ('$timestamp','$REMOTE_ADDR','$PHP_SELF')",$db);
if(!($insert)) {
print "Useronline Insert Failed > ";
}
$delete = mysql_query("DELETE FROM useronline WHERE timestamp<$timeout",$db);
if(!($delete)) {
print "Useronline Delete Failed > ";
}
$result = mysql_query("SELECT DISTINCT ip FROM useronline WHERE file='$PHP_SELF'",$db);
if(!($result)) {
print "Useronline Select Error > ";
}
$user = mysql_num_rows($result);


mysql_close();
if($user == 1) {
print("$user user online\n");
} else {
print("$user users online\n");
}
?>


//The table structure 

CREATE TABLE useronline (
timestamp int(15) DEFAULT '0' NOT NULL,
ip varchar(40) NOT NULL,
file varchar(100) NOT NULL,
PRIMARY KEY (timestamp),
KEY ip (ip),
KEY file (file)
);