Simple PHP file counter

I got this request from a friend who wanted a simple counter for one of his web pages. He didn’t want the counter visible but wanted to be able to check how many times it was viewed.

Hi Marty. . What I want is a simple text counter that will just count the number of times a page is viewed. Do you have a simple solution?

Below is a very simple counter utilising a simple text file. What is does in simple terms is a) open a file for writing b) takes the current count and adds 1 c) closes the file. This is a quick fix that’s prone to a number of errors. For any serious tracking you would almost certainly use a database backend and record additional details.

<?php
$counter = ("hitcounter.txt");
$hits = file($counter);
$hits[0]++;
$fp = fopen($counter , "w");
fputs($fp , "$hits[0]");
fclose($fp);
// echo $hits[0];
?>

What this little script does is as follows:

Open PHP tag

<?php

This line defined the file to be used to record individual views.

$counter = (“hitcounter.txt”);

Now we defined the $hits variable — this is the contents of the file that we will later extract as part of an array.

$hits = file($counter);

We take the first element of the array (the number of hits to our site) and we add 1 (++). You must have write access.

$hits[0] ++;

Opens the $counter text file for writing.

$fp = fopen($counter , “w”);

fwrite will write the contents of string ($hits) to the file ($counter).

fputs($fp , “$hits[0]“);

Closes the file ($counter).

fclose($fp);

I’ve commented out this line, but if you wanted to display the number of hits in ($counter) you would remove the comment lines (//)

// echo $hits[0];

Close PHP tag.

?>

Again, this is a simple solution. I’ve used it as a quick-fix to check the number of times a file was downloaded. To do this I redirected the file link to a php page called redirect.php and as the last line of code I inserted the following:

header(“Location:http://www.domain.com/path_to_download_file.pdf”);

If you wanted to display a big and bloaty messy image as a counter rather than the text (can you tell I don’t like them?), you would just create an array from the $counter file and associate each number with an image.


Download: Basic Counter
Description: Basic PHP counter.
Author:InterNoetics
Category: PHP code
Date: January 2, 2010

If you liked this article, you may also like:

  1. Simple WHOIS PHP Script
  2. Zip a file or files with PHP
  3. Unzip a file with PHP
  4. Better WordPress Custom Coding – custom functions/css file
  5. Force the Download of a File with PHP
About Marty

is a passionate web developer from Sydney, Australia. He owns about 400 websites and makes a healthy living from working the web. As a day job, he works as a pilot for an international airline. You can follow Marty on Twitter or Google+.

Speak Your Mind

*