Simple PHP Hit Counter

No need for a service when you can do it for free!

On many pages it is common to have a generic hit counter displayed at the bottom of each page. Now it goes without saying that this is a very simple metric that arguably has zero intrinsic value. If a user spams F5 on your beloved homepage (or a sneaky web dev wants to impress his friends), this piece of code will just keep incrementing its value.

Of course, these days there’s tons of tools available to analyse web hits from various dimensions – hits by the country, unique hits, hits by second/day/month/year/etc.

Nevertheless, sometimes you just want to whip up a quick script with 0 effort.

The code is below:

// open file
$fp = fopen("hitcount.txt", "r");
$count = fread($fp, 1024); 		// grab current hit counter value
fclose($fp);
$count = $count + 1;			// close file and increment counter by 1

// Display the number of hits
echo "Page views: $count";

// write new counter vale to file
$fp = fopen("hitcount.txt", "w");
fwrite($fp, $count);
fclose($fp);

Enjoy!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s