Show the Number of Users Online

Learn how to add upload a file using the power of PHP.

Spreadshirt
This script will explain how to display the number of users online using your website. You have to put this on everypage you want it to appear. It can be broken down into 2 sections. The first is creating the table, and the second is the PHP script itself. Beware you should have knowledge of PHP before attempting this. We also reccommend you have PhpMyAdmin :)

Alright log on to PhpMyAdmin and make a new database called "users". We are going to insert 3 fields into a new table called useronline called timestamp, ip, and file. Lets dump the following code into the Users database using the form on the PhpMyAdmin page:
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)
);



Alright Now lets create the PHP script. Its rather large and lets hope you can follow along. Here is what we'll do in English:

1. Give the server info.
2. Get the time.
3. Insert the values of the person thats online into the mySQL, then create the Failed response if it failed.
4. Do the same thing but delete the user from the database when he leaves
5. Grab the results.
6. Output the results.

Finally, here is the PHP Code:
<?php
//fill in some basic info
$server = "localhost";
$db_user = "username";
$db_pass = "password";
$database = "users";
$timeoutseconds = 300;

//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 "Useronline Insert Failed > "; }

//delete values when they leave
$delete = mysql_db_query($database, "DELETE FROM useronline
WHERE  timestamp<$timeout"); if ( !($delete) ) { print "Useronline Delete Failed > "; }

//grab the results
$result = mysql_db_query($database, "SELECT DISTINCT ip FROM
useronline WHERE  file='$PHP_SELF'");
if ( !($result) )
  { print "Useronline Select Error > "; }

//number of rows = the number of people online
$user = mysql_num_rows($result);

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

Not too tough was it? Well thats it folks. I hope it works out for you and if it doesn't, post on the baord and we'll try to help you out.