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()
 //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");
  echo $numusers . " user online";
  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.