getButterfly Logo getButterfly code wrangling since 2005

If, for any given reason, you are not able to implement a MySQL counter, here is the easiest solution for creating a flat file online users counter. Create a file called online.php, make it writable (either CHMOD 755 or CHMOD 777, depending on your server requirements), and insert the following code where you want the counter to appear.

Here is the code:


$file_name = "online.php";
$c_time = time();
$timeout = 60;
$time = $c_time – $timeout;
$ip = getenv("REMOTE_ADDR");

if(!file_exists($file_name)) {
$fp = fopen($file_name, "w");
fwrite($fp, " \n");

$fp = fopen($file_name, "a");
$write = $ip."||".$c_time."\n";
fwrite($fp, $write);

$file_array = file($file_name);
$online_array = array();
for($x = 1; $x < count($file_array); $x++) {
list($ip, $ip_time) = explode("||", $file_array[$x]);
if($ip_time >= $time) {
array_push($online_array, $ip);

$online = array_unique($online_array);
$online = count($online);
if($online == "1") {
print "$online user online";
else {
print "$online users online";

I have successfully used this code on many sites for years without errors. So, trust me on this!

Photo credit by ja1vbn

Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.

If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

Leave a reply