For this script we'll be using a text file to store the hits count, when the user visits the page it will call our counter script.
It will take the count from the file, increase it by one and store it back in the file. Then it will print the amount of hits on the page.
Let's look at the code, then we'll go over it.
<?php
|
|
The first thing we have, of course, is the opening php tag. Followed by the declaration of a variable. ($file) This variable holds the path to our counter file, that will remember how many hits we've recieved.
The next block of code is an if statement that uses the function
file_exists() to find out if the file held in the variable $file does not exist.
(Note the exclamation point in front of the function makes it check if the output returned by the function is false)
If it doesn't exist, the script will create the file using fopen() in 'w' mode. It will then use fwrite to write '0' to the file. Then it will close the file handle, using fclose().
Next we use file_get_contents() to grab our current hit count, then we increment it by one.
The next chunk of code will check to make sure the file is writable using is_writable(). If it is writable, the script will open the file and write the incremented hit count to the file, then close it. If it is not writable, it will display an error message using echo().
Finally, we use number_format() to make the number more easy to read and print the count to the page.
That's it, you've got a fully functional hits counter.
I hope this tutorial helped you. If you have any questions use the "Discuss this tutorial" link in the right column. 
| Discuss Tutorial: Hits Counter | 13 Comments |




