|
How Many Users Online?
|
|
Home Page :: Authors Login :: Author Signup :: Search :: More Articles
Home :: PHP/MySQL
|
How Many Users Online?
By Ben Sinclair
Contact Ben Sinclair
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!
Enjoy!
Discuss this in our Webmaster Forums
About The Author:
Ben Sinclair
Ben Sinclair is the Webmaster of Webmaster Resources 101(/)
|
|
|
Advertising
|
|
Advertise your website here. View Advertising Information.
|