Very Simple PHP Visit Counter

To create a simple PHP visit counter you will need to create a plain blank text file called counter.txt.

Put the following two functions into a file and include it at the top of any page that you want to have counted.

The loadCounter() function.
function loadCounter()
{
 if ( file_exists('counter.txt') ) {
  $n = file_get_contents('counter.txt');
  return intval($n);
 }
 return 0;
}

The updateCounter() function.

function updateCounter($i=1)
{
 
 $n = loadCounter();
 $n += $i;
 
 $fp = fopen('counter.txt',"w+");
 fwrite($fp, $n);
 fclose($fp);
 
 return $n;
}

The two functions work together to create the counter. If you only want to display the number of times that a page has been visited then just call the loadCounter() function.

echo loadCounter();

On any page that you want to log as a visit include a call to the updateCounter() function. This will also return the number of visits that the page has had.

echo updateCounter();

Because we are using the w+ flag with the fopen() function PHP will try to create the file counter.txt if it doesn't exist. However, it is best not to leave this to chance so as it will generate errors if the script doesn't have access to create the file, or you are running in safe mode.

If you want to get more complicated than this then you may as well use an analytics package such as Google Analytics. This mechanism isn't really all that useful (except on very small sites) but it is good example of how the fopen() function works.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
3 + 4 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.