Home Blog Super Simple PHP File Counter (With WordPress Example)

Super Simple PHP File Counter (With WordPress Example)


We first posted a version of this code back in 2008. It’s super-simple code that’ll record the number of hits to a page with an incremental count stored in a text file. In reality, it’s not an overly practical solution for anything… but it is useful in wrapping your head around how the file functions of PHP work. For the sake of demonstration, we’ve added a WordPress post/page count function that’ll also cache data in a text file.

The functions simply opens a file for writing, takes the current count and adds one, then closes the file. Simple.

The PHP Function

The Code Explained

Following is an explanation of the code for those of our clients that are introducing themselves to the basics of PHP.

We need to define a location and name for our text file. If the file_exists() , we’ll use its location, otherwise we’ll create an array with a single value of 0. The filename ($file) and $path to the file are both function arguments.

To get the existing count, we first check that the file exists. If the text file does exist, we’ll use file() function to read the entire text file into an array. If it returns false, we’ll create a single array value ($hits['0']) We create the 0 count as a an array value because that’s how we’ll increment it to 1 on the next line. We’ve used a PHP ternary operator that fits the format $variable = (statement) ? 'return_true_value' : 'return_false_value';.

The $hits[0]++ will take the value of $hits[0] and then increments the value by one.

The fopen() function opens a file or URL. The function requires a second argument (the mode parameter) which specifies the type of access you require to the data stream. In our case, we’re using fopen($counter , "w"), where “w” will “open [the file] for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it”.

Super Simple PHP File Counter (With WordPress Example)

fopen() mode arguments: Source: http://php.net/manual/en/function.fopen.php

The if statement applies in cases where fopen returns false (the value of $fp). If $fp returns false we’ll skip to returning the result. Otherwise we’ll process to write the data. The two lines in the statement are as follows.

The fwrite() writes the contents of string (the incremented value of $hits[0]) to the file stream pointed to by handle (the handle is defined by fopen, in our case “..places the file pointer at the beginning of the file”.

The fclose() function closes an open file pointer.

If the function argument of $display is true (or isn’t false), we’ll print the result.


Usage is easy.

The function requires three arguments: $file, $display, and $path – the latter of which will normally be static.

The only error checking is on the file pointer. File functions are prone to errors so it would be prudent to conduct error checks on each step if something like this were used in the real world.

Return The Count With PHP

To return the count for a particular page, use the following:

The primary function will return the count with $display = true, so this function is better used to return the count of another page. You will be required to define the cache location.

Used as a WordPress Counter

We have a (soon-to-be-updated) WordPress Plugin, Simple Post Counter, hosted in the WordPress repository. It will incrementally count hits to your posts and pages, and it will add a view count to your admin and edit pages. Having a text file to do the job of a database is almost always a bad idea. However, for the sake of a demonstration, we’ll produce a really simple WordPress post count.

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin.

You are required to add the location of your $cache directory. The resulting cache text file will be in the format post_id-slug_name.txt so it’s easily identified.

Return Post Count in WordPress

If you were to print the post or page count to a page, the function below could be used. Shortcode usage is [bmcount]. To show the count of a page other than the page you’re on, use [bmcount id="1234"] (where ‘1234’ is the post id of the other page). You may optionally use n="true" to return a formatted number .

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin.

If you require shortcode to work in a sidebar widget, you'll have to enable the functionality with a filter. If you're using our custom functions plugin, you'll have that feature enabled by default.


  • You shouldn’t use our simple text file count function in the high-volume real world (particularly with WordPress). The file functions are unreliable, and a count in isolation rarely provides sufficient feedback of anything. Employing a database and collecting as much information you need from each visit is a better option. In terms of WordPress, use our plugin: Simple Post Counter.
  • If you were counting links to a download, you could use something like header("Location:http://www.domain.com/path_to_download_file.pdf"); in your code once the count has been made. On error, maybe print a message.
  • If you wanted to display an image for the count, and didn’t want to navigate GD waters, something similar to the following will work (the $count is the returned value, and $num refers to a corresponding image):

  • While you would never normally bother, the data you store in your text file could be a serialized array with larger amounts of data (such as incremental post count by country or OS). It’s an unreasonable solution but easy to do with our Simple Cache With PHP functions.
  • Instead of returning false in the WP shortcode version (if retrieval was unsuccessful), you could consider returning the text ‘Unavailable’.
  • Prevent counting your own hits by creating an array of your IP addresses, then write a condition after if ($fp !== false) that’ll check for a returned IP using in_array();.


Title: Super Simple PHP File Counter
Description: Record the number of hits to a page with an incremental count stored in a text file.
Download: PHP Code (V0.2) | Plugin Page

Shortt URL for this post: http://shor.tt/2nND


Please enter your comment!
Please enter your name here