PHP MySQL Online Script

You can use this little script to show number of users online, all you need to do is to insert this piece of code in your script and echo $online variable.

//If table 'online' doesn't exist, create it.
mysql_query("CREATE TABLE IF NOT EXISTS `online` (
  `timestamp` int(15) NOT NULL default '0',
  `ip` varchar(40) collate utf8_unicode_ci NOT NULL default '',
  `uri` text collate utf8_unicode_ci NOT NULL,
  PRIMARY KEY  (`timestamp`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");

$request = htmlspecialchars($_SERVER['REQUEST_URI'],ENT_QUOTES); // Current page URL
$timeout = 60; // Timeout in minutes
$timeout = $timeout * 60; // Convert to seconds

//Run insert query
mysql_query("INSERT INTO online(timestamp,ip,uri) VALUES('".time()."','".$_SERVER["REMOTE_ADDR"]."','$request')"); 
//Delete entries older than timeout period
mysql_query("DELETE FROM online WHERE timestamp < $timeout");
//Sum all online IPs
$online = mysql_query("SELECT COUNT(0) FROM online GROUP BY ip");
$online = mysql_num_rows($online);

echo $online; // Voila


For example look in footer of this page
©2009-2011 Webarto • web design & development • Tuzla // Sarajevo // Beograd