|
PHP -> Basics -> Simple PHP Hit Counter Script
Simple PHP Hit Counter Script
- Apr 15 2006
This tutorial will show you how to create a very simple hit counter in PHP.
Tutorial Monkey is a database of technology-related tutorials. We write our own tutorials as well as linking to other ones in the web. If you would like to submit a link to your tutorial, feel free to do so. Just click on "submit" at the top of the page. Note: Images may result in loss of quality due to the fact that we must resize them to fit the design. You can click resized images to see its original image in a new window. Sponsors Step 4
Because we are viewing the file, we have to add a new hit to the counter. Take a look at the following code and try to figure out yourself what it means:
<?php
The new line that I've added -- "$hits = $hits + 1;" should be easy to decipher. I am redefining the variable $hits. This time, $hits is "$hits + 1". The line basically says in plain english -- $hits should now be whatever's inside the file "hits.txt" plus one. What's inside the file? Well, it was only 0... which means $hits should equal 0 + 1.. = 1. Step 5
Now that we've updated the hits count to add one, lets update hits.txt to the NEW hits count. Take a look at this code:
<?php
The function fopen opens the file "hits.txt" in the first argument. The "w" tells PHP that we are only opening the file to write, and nothing else. It also tells PHP to erase everything in the file and set the pointer (something like little flashing black line you see when you type in a text box) to the beginning. Why do we need a variable? Because we need a handle from fopen to execute other commands like -- in this case -- fwrite(). To write, you have to tell PHP that you've previously opened the file -- and give PHP the handle. The line "fwrite($handle, $hits);" tells PHP to write to the file specified in the $handle ("hits.txt") and it also tells PHP to write $hits into the file. $hits -- as we've already discovered -- is the old hit number plus one. Now you can see somewhat of a hit counter resemblance. Adding one hit to the old number. fclose() tells PHP that we're done with the file, so close it. Side Note -- in PHP 5, it is possible to fopen, fwrite and fclose all at once with the function file_put_contents This tutorial is paginated, please navigate [ Steps 1-2 ] [ Steps 3-4 ] [ Steps 5-6 ] [ Steps 7-8 ] « Back |