PHP Code

Build a Simple Hit Counter With PHP

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.

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

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


  1. Hey Justin, I love this code. Very simple and effective. Quick question; is it possible to set this to reset itself every 24 hours, or at a set interval? Thanks. =)

  2. Hey thanks for the script. I was looking for awhile before I found one that worked. I had some trouble using a mysql one because my host is crap so this simple really hit the spot. Thanks!

  3. Hi,

    Thanks for the smart little piece of code. I needed something in a hurry with minimum overhead and it was on the server and working in three minutes. No even any CHMODing. My boss in impressed! 🙂



  4. I have typed the website name in the website field.

    I am having trouble making the PHP function work on the website as I have little knowledge of PHP, any chance you could give me some help via email to how to sort my problem out?

  5. Hey,How can I output the daily hits in a table type..I want to retrieve the data and see from the start of the month until the present day.

    thanks for any help

  6. I tried it but after a few thousand hits, the counter would reset itself… hmmm…

Leave a Reply

Your email address will not be published. Required fields are marked *

To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image