RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts</strong | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.69% (5.89%*) • Home Loan Fixed: 5.39% (6.67%*) • Fixed: 5.39% (6.67%*) • Variable: 5.69% (5.89%*) • Investment IO: 5.69% (6.52%*) • Investment PI: 5.49% (5.98%*)

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

1
<?php 
2
/*
3
 Super Simple PHP File Counter
4
 http://www.beliefmedia.com/php-file-counter
5
*/
6
 
7
function beliefmedia_text_counter($file = 'count', $display = false, $path = '/home/public_html/path/to/php-file-counter/cache') {
8
 
9
  $counter = $path . '/' . $file . '.txt';
10
  $hits = (file_exists($counter)) ? file($counter) : array('0');
11
  $hits[0]++;
12
  $fp = fopen($counter , &quot;w&quot;);
13
 
14
  if ($fp !== false) {
15
    fwrite($fp , $hits[0]);
16
    fclose($fp);
17
  }
18
 
19
 if ($display !== false) echo $hits[0];
20
}
21
 
22
/* Usage */
23
beliefmedia_text_counter();
24
?>

The Code Explained

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

9
$counter = $path . '/' . $file . '.txt';

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.

10
$hits = (file_exists($counter)) ? file($counter) : array('0');

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';.

11
$hits[0]++;

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

12
$fp = fopen($counter , "w");

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

14
if ($fp !== false) {
15
  fwrite($fp , $hits[0]);
16
  fclose($fp);
17
}

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.

15
fwrite($fp , $hits[0]);

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".

16
fclose($fp);

The fclose() function closes an open file pointer.

1
if ($display !== false) echo $hits[0];

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

Usage

Usage is easy.

1
/* Usage */
2
beliefmedia_text_counter();

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:

1
<?php 
2
/*
3
 Super Simple PHP File Counter
4
 Returns Count for $file
5
 http://www.beliefmedia.com/php-file-counter
6
*/
7
 
8
function beliefmedia_text_counter_count($file = 'count', $path = '/home/public_html/path/to/php-file-counter/cache') {
9
 return trim(file_get_contents($path . '/' . $file . '.txt'));
10
}
11
 
12
/* Usage */
13
echo beliefmedia_text_counter_count($file = 'count');

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.

1
<?php 
2
/*
3
 Super Simple PHP File Counter (for WordPress)
4
 http://www.beliefmedia.com/php-file-counter
5
 Requires that you define a cache location
6
*/
7
 
8
function beliefmedia_wordpress_textfile_count() {
9
 
10
 global $post;
11
 $id = $post->ID;
12
 $slug_name = $post->post_name;
13
 
14
 /* Path to text file cache */
15
 $path = '/home/public_html/path/to/your/cache';
16
 
17
 /* The path to the count file */
18
 $counter = $path . '/' . $id . '-' . $slug_name . '.txt';
19
 
20
  $hits = (file_exists($counter)) ? file($counter) : array('0');
21
  $hits[0]++;
22
  $fp = fopen($counter , "w");
23
 
24
  if ($fp !== false) {
25
    fwrite($fp , $hits[0]);
26
    fclose($fp);
27
  }
28
}
29
add_action('wp_footer', 'beliefmedia_wordpress_textfile_count');

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.

1
<?php 
2
/*
3
 Super Simple PHP File Counter (for WordPress)
4
 http://www.beliefmedia.com/php-file-counter
5
 Requires that you define a cache location
6
*/
7
 
8
function beliefmedia_wordpress_textfile_count_show() {
9
  extract( shortcode_atts( array(
10
    'path' => '/home/public_html/path/to/your/cache',
11
    'n' => false,
12
    'id' => false
13
  ), $atts ) );
14
 
15
 global $post;
16
 
17
 /* ID current post if false */
18
 if ($id === false) $id = $post->ID;
19
 
20
 /* Get slug name */
21
 $slug_name = ($id !== false) ? get_post_field( 'post_name', $id ) : $post->post_name;
22
 
23
 /* The path to the count file */
24
 $counter = $path . '/' . $id . '-' . $slug_name . '.txt';
25
 
26
 /* Get count*/
27
 if (file_exists($counter)) {
28
 
29
   /* file_get_contents returns a string */
30
   $count = file_get_contents($counter);
31
   return ($n != false) ? number_format($count) : $count;
32
 
33
 } else {
34
   return false;
35
 }
36
}
37
add_shortcode('bmcount', 'beliefmedia_wordpress_textfile_count_show');

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.

Considerations

  • 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):
1
$hit = str_split($count, 1);
2
  foreach ($hit as $num) {
3
  $visits .= '<img src="' . $num . '.jpg'">';
4
}
  • 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();.

Download


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 • Version 0.2, 544.0B, zip, Category: PHP Code & Snippets

■ ■ ■

 
Download our complimentary 650-page guide on marketing for mortgage brokers. We'll show you exactly how we generate billions in volume for our clients.
Finance Guide, Cropped Top and Bottom
  Timezone: 1 · [ CHANGE ]

RELATED READING

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment