Here's the full code, it works fine for me, it is compatible with pretty much all versions of PHP. This script is basic, but does all that is needed and does it quickly.
Place the code in a file that is accessed most often.
Remember to format the print into the file you want.
<?php
// Table structure dump:
// CREATE TABLE online_users (ipaddress VARCHAR(15) NOT NULL, datetime VARCHAR(10) NOT NULL)
// Set to expire sessions after every so many minutes of inactivity.
$expire = "5";
// Format the expiration into seconds.
$expired = time()-($expire*60);
// Delete expired sessions.
$query = mysql_query("DELETE FROM online_users WHERE datetime<=$expired");
// Find the "bullet-proof" IP address.
function iptype1 () {
if (getenv("HTTP_CLIENT_IP")) {
return getenv("HTTP_CLIENT_IP");
} else {
return "none";
}
}
function iptype2 () {
if (getenv("HTTP_X_FORWARDED_FOR")) {
return getenv("HTTP_X_FORWARDED_FOR");
} else {
return "none";
}
}
function iptype3 () {
if (getenv("REMOTE_ADDR")) {
return getenv("REMOTE_ADDR");
} else {
return "none";
}
}
function ip() {
$ip1 = iptype1();
$ip2 = iptype2();
$ip3 = iptype3();
if (isset($ip1) && $ip1 != "none" && $ip1 != "unknown") {
return $ip1;
} else if (isset($ip2) && $ip2 != "none" && $ip2 != "unknown") {
return $ip2;
} else if (isset($ip3) && $ip3 != "none" && $ip3 != "unknown") {
return $ip3;
} else {
return "none";
}
}
$ipaddress = ip();
// Check to see if user all ready has a session.
$query2 = mysql_query("SELECT * FROM online_users WHERE ipaddress='$ipaddress'");
if (mysql_num_rows($query2)==0) {
// If user doesn't have a session, create one.
mysql_query("INSERT INTO online_users (ipaddress, datetime) VALUES ('$ipaddress', '" . time() . "')");
} else {
// If user does have a session, update it to the new time.
mysql_query("UPDATE online_users SET datetime='" . time() . "' WHERE ipaddress='$ipaddress'");
}
// Print number of online users.
echo mysql_num_rows(mysql_query("SELECT * FROM online_users")) . " Users Online";
?>