How to Write a Simple Hit Counter in PHP (Working With Files)

When I started programming websites, one of my biggest interests was to know how many visits my website had. When you are a beginner, it’s complicated to find a single hosting product including database service for free, so the better approach for this problem is use a plain text file as db.

The process is really easy: every time a webpage loads, the database file is opened, read its content, increased by one, and saved again to disk.

Let me show the code:

// database file, itself

$count_my_page = (“hitcounter.txt”);

// open file and increasing it for every visit

$hits = file($count_my_page);

$hits[0] ++;

// reopen database file, this time for writing

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

// write into disk

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


// show value

echo $hits[0];


As you can see, this is an excellent example to meet file functions in PHP. We use four of them:

1. file – to read a file content all lines at once, an returns an array with them

2. fopen – returns a pointer to a file, with proper permissions (write, in this case)

3. fputs – write a string into a file pointer

4. fclose – close a file pointer after using it

The example is painless, but it’s a nice start point to know more about file processing.

Sure you noticed that there is a small “trick”: every time the page loads, the counter is increased by one. This means that it is extremely useful for tracking impressions, but not so good for counting real visits, because a visit could go through different web pages inside the same website.

For this goal the server uses to record the origin IP addresses and counts a new visit only when a specified time has passed, like 5 minutes or similar.

Of course, this also could be developed only with plain files, storing the server time and making use of array $_SERVER[‘REMOTE_ADDR’].

If you want to master the skills to do it and know more about PHP, from simple scripts to high programming techniques, I recommend take a look at this.

Source link