How Many Users Online?

by Ben Sinclair
Webmaster-Resources101.com
Thursday, 28th July 2005

You can easily show how many users are online with PHP and MySQL! The MySQL Part First of all you will need to create a table in your MySQL Database:

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`)
) TYPE=MyISAM;

Showing The Users You now need to create a file called useronline.php. Fill out the configuration with your own information:

<?
// -------------------------------------
//  Configuration
// -------------------------------------
$dbhost = "localhost";
$dbuser = "";  // MySQL Username
$dbpass = "";  // MySQL Password
$dbname  = ""; // Database Name
$timeoutseconds  = 300;   // How long till it will remove the user from the database(In seconds)
// -------------------------------------
$timestamp=time();
$timeout=$timestamp-$timeoutseconds;
// Connect to MySQL Database
mysql_connect($d_host,$dbuser,$dbpass);
@mysql_select_db($dbname) or die("Unable to select database");
// Add this user to database
mysql_query("insert into useronline values('$timestamp','$REMOTE_ADDR','$PHP_SELF')") or die("<b>MySQL Error:</b> ".mysql_error());
// Dlete users that have been online for more then "$timeoutseconds" seconds
mysql_query("delete from useronline where timestamp<$timeout") or die("<b>MySQL Error:</b> ".mysql_error());
// Select users online
$result = mysql_query("select distinct ip from useronline") or die("<b>MySQL Error:</b> ".mysql_error());
$user = mysql_num_rows($result);
// Select users on this very page
$resulta = mysql_query("select distinct ip from useronline where file='$PHP_SELF'") or die("<b>MySQL Error:</b> ".mysql_error());
$usera = mysql_num_rows($resulta);
mysql_close();
// Show all users online
if ($user==1) {echo"$user user online!</font>";} else {echo"$user users online.";}
// Show users on this very page
if ($usera==1) {echo"<br>$user user viewing this page!</font>";} else {echo"$user users viewing this page.";}
?> Now you need to include it on everypage: <?php
include("useronline.php");
?>

That's everything! Just update the Database COnfiguration and you're all set.

Enjoy!


Options:
Printer Friendly
Email Friend

About The Author:

Ben Sinclair is the webmaster of Webmaster-Resources101.com, Webmaster-Forums101.com and DevTutors.com

Developer Categories



Developer Tutorials
ASP
CGI & Perl
CSS
Flash
HTML
Java
JavaScript
MySQL
PHP
Python
XML

Developer Documentation

Developer Tools



Search our Developer Tutorials
  The DevSyndicate Network