A working example: making a counter

Counter scripts really are quite simple once you get down to it - you store a value representing the number of times a page has been visited, and show it to your visitors somewhere on the page. Naturally, given the current topic is file manipulation, we are going to store that variable inside a file. To open, read from, write to, and close files, we will be using some new functions - fopen, fread, fwrite, and fclose respectively - the f, of course, stands for "file".

Here is an example counter script, making use of the new functions:

    // your content here...
    $filename = '/path/to/counter.txt'; // our counter file
    $fp = fopen( $filename,"r"); // open it for READING ("r")
    $counter = fread($fp, filesize($filename) ); // read in value
    fclose( $fp ); // close it whilst we work

    ++$counter; // increase the counter by one
    print "$counter hits to this page"; // print out the new value

    $fp = fopen( $filename,"w"); // open it for WRITING ("w")
    fwrite( $fp, $counter); // write in the new value
    fclose( $fp ); // close it

Edit the $filename variable to point to a file you have created somewhere (make sure the PHP user ID is able to read from it and write to it), then save the above script as counter.php and run it in your web browser. At first you should see "1 hits to this page", but each time you refresh, the value should go up and up - you can reset the value by deleting the contents of the file (not the file itself).

Let's break down the script, line by line. First we create a $filename variable to hold the name of the counter file. Following that, we use fopen() for the first time, specifying its first two parameters: our $filename variable, and the mode of opening. The name of the file is simple enough, but the _mode_ parameter requires a little explanation - you need to specify whether you wish to read from the file, write to the file, or append to the file, and there are various modes to allow you to do so. In the example above, we use the "r" mode for reading, then the "w" mode for writing. You are able to combine the two together to make "rw", which would open a file and let you read _and_ write to it.

Fopen() returns a file handle if it successfully opened the file in the mode you requested, otherwise it returns false. Our file handle is used immediately, in our fread() line. fread() takes a file handle as its first parameter, and the number of bytes to read from that file handle as its second parameter. Of course, the number of bytes to read is just what we wanted, because that is just what filesize() returns!

So, in counter.php, we fread()filesize() bytes from $filename and place them into $counter. By using filesize() as the second parameter, we read the entire file into our variable - just the ticket for a counter.

We use fclose() to close the file pointer. This allows other processes access to the file while we aren't using it, and it is generally best practice to keep files open for as short a time as you are able - it is very easy for something to go wrong and corrupt a file you left dangling open.

Author's Note: Even though PHP automatically cleans up for you when your script finishes (objects are deleted, MySQL connections are closed, files are fclose()d, and so on), I strongly recommend against leaving things lying around for PHP to clean up - do your own housekeeping now, and it will help you later on.

With our file pointer closed, we are back onto easy PHP code - we take the contents of $counter and increment it by one. Here is a great example of PHP's lack of strongly-typed variables - fread() returns a string, and yet we can increment that string as if it were an integer. After incrementing $counter, we print it out to the screen using print.

Next we update our counter file, which is done in three stages, again starting with fopen(), but this time we are using the "W" mode to enable writing. We follow that up with a call to fwrite() passing in our file handle as the first parameter, and the information to write as the second parameter.

Finally, we close our file handle using fclose(), and our counter script is complete. Now you just need to replace "// your content here..." with a witty and popular web site, and you will be a smash hit!


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Handling file uploads >>

Previous chapter: Dissecting filename information

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.