Build a Simple Hit Counter With PHP

by admin on July 24, 2009 · 0 comments

Here is a quick text-based solution to have a simple hit counter on a single page. This is not meant to provide any sort of advanced web analytics, merely a count of how many times a web page has been loaded.

Create an empty text file in the same directory as the PHP page that you want to count hits on. Call it whatever you want. You could duplicate this counter accross pages, just create a unique text file for each page you want to track.

The function gets the text file, opens it for reading and writing, saves its contents, closes it, opens it again, adds 1 to the total count, displays the hit count and then finally saves and closes the file again.

<?php
$text_file = "hits.txt";
 
function hitCount($file) {
     $fp = fopen($file,rw);
     $count = fgets($fp,9999);
     fclose($fp);
     $fp = fopen($file,w);
     $count += 1;
     print "$count ";
     fputs($fp, $count);
     fclose($fp);
}
 
/* display it on your page */

echo 'Page hits:' . hitCount($text_file);
?>

Previous post:

Next post: