You've seen those neat things on websites that tell how many users are currently browsing that site. It's actually a fairly simple script that runs the online users counter. The basic sequence of the script goes like this:

Assume there is a database that holds an IP and a time
1. User loads page
2. Insert IP into log with time NOW()
4. Delete entries from the log where the timestamp is greater than a specified timeout
5. Select IP's from log with the DISTINCT flag.
6. Echo out a mysql_num_rows of your result.

This can be expressed in code by the following example:

function useronline()
{
 $timeoutseconds=300;
 $timestamp=time();
 $timeout=$timestamp-$timeoutseconds;
 $ip=$_SERVER['REMOTE_ADDR'];
 //database connection here
 mysql_query("INSERT INTO usersonline (timestamp, ip) VALUES ('$timestamp','$ip'");
 mysql_query("DELETE FROM usersonline WHERE timestamp<$timeout");
 $res=mysql_query("SELECT DISTINCT ip FROM usersonline");
 $numusers=mysql_num_rows($res);
 if($numusers==1)
 {
  echo $numusers . " user online";
 }
 else
 {
  echo $numusers . " users online";
 }
}

lj suggests the use of sessions or cookies in this tool. These options would definitely deliver more accurate results, for, as he pointed out, many ISPs proxy web requests transparently. This is just a very basic script, a hack even. Please feel free to improve it for your own use.

Log in or register to write something here or to contact authors.