Very Simple PHP Visit Counter

26th May 2008 - 2 minutes read time

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.
  1. function loadCounter()
  2. {
  3. if ( file_exists('counter.txt') ) {
  4. $n = file_get_contents('counter.txt');
  5. return intval($n);
  6. }
  7. return 0;
  8. }

The updateCounter() function.

  1. function updateCounter($i=1)
  2. {
  3.  
  4. $n = loadCounter();
  5. $n += $i;
  6.  
  7. $fp = fopen('counter.txt',"w+");
  8. fwrite($fp, $n);
  9. fclose($fp);
  10.  
  11. return $n;
  12. }

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.