Really Simple PHP Counter

A few days ago I needed to find a simple way to count the number of times a web page loaded. A script in the page had a variable that triggered an event to occur every so many page loads. I needed to use a counter to trigger the event the variable controlled. This little 93 Byte counter code is what I came up with:

<?php
file_put_contents('count.txt','1\n',FILE_APPEND);
$count = count(file('count.txt'));
?>

The first time the counter script runs it creates a file called count.txt then writes a number “1” and a carriage return into the first line of the file. From then onwards, every time the script runs it appends another number “1” and a carriage return to count.txt. The script counts the non blank lines in count.txt with every run.

Doing Useful Things With The Counter

The value of $count can be used to do useful things with the counter. For example:

To see the number of times the counter has been activated (106 Bytes),

<?php
file_put_contents('count.txt',"1\n",FILE_APPEND);
$count = count(file('count.txt'));
echo $count;
?>

To display a message when the counter reaches a particular value such as every tenth run (178 Bytes),

<?php
file_put_contents('count.txt',"1\n",FILE_APPEND);
$count = count(file('count.txt'));
if ($count == 10) {unlink('count.txt');echo 'The counter has run another 10 times';}
?>

To make your own free page hits counter to display at the bottom of your page, place this bit of PHP code in the footer of your page and, optionally, style table id php-counter (162 Bytes):

<?php
file_put_contents('count.txt',"1\n",FILE_APPEND);
$count = count(file('count.txt'));
echo '<table id="php-counter"><tr><td>'.$count.'</td></tr></table>';
?>

The third line of the above code (echo ‘<table……’;) displays the counter in a table. That table may easily be formatted to match your own aesthetic preferences.

It didn’t take me long to realize I can use the counter as the basis for a free self-hosted PHP webpage hit counter and visitor tracker. It took a couple of hours but eventually I scripted something that works well enough to share. Read more about the Really Simple Visitor Tracker and download it here.

I’m still discovering PHP and perhaps there’s a better way to make a PHP counter that doesn’t reset every time the script that uses it runs. I will let you know when I learn of one. Feel free to showoff if you already have a few ideas.

Sharing is caring!

1
Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
newest oldest most voted
Notify of
sdf

fsd