PHP page hits counter script using text fileCounters are required to count the number of visitors coming to the page or the browsers open the number of time the page. The PHP script we will be discussing here is one simple page counter and it will not take in to account if same visitors in same session opening the page again and again. This will also not check the IP and increase the count with unique IP only. These are part of advanced counter script we will discuss separately. We will discuss here one simple page counter or hit counter. In the second part of the script we will discuss graphical counter in which we will discuss on how to manage attractive displays showing the count value.
We will use flat text file to store the data ( count of the page ) and will not use any database here for simplicity.
For a better understand on how to read from a file and on how to write to a file, please read the articles here before working on the counter script.
We will use the page counter.php to store our script and we will keep our data ( counter value ) in the text file counter.txt. Both the files will be in same directory.
Create one text file in the same directory of the page where the counter to be displayed and give the name counter.txt. If you are using this script in Linux system then give write permission to this file. If you are testing this script in your local window machine then this may not be required as by default write permission will be there. If you are running this script in a windows hosting account then ask the administrator to give write permission to this file. This is important as we will be writing this file with new data on every page request of the main file.
Here is the code to open the counter.txt file and then displaying the data by incrementing it by one. We will use file read function fread() here to read the data from the text file. Before that we will use fopen to open the file in reading mode.
$filename = "counter.txt"; // This is at root of the file using
That's all, very simple. You can create counter for any page like this. But we will move to next step. We will try to create attractive graphical counter or call it digital counter using the same script but adding little more to display images in place of numbers digits. Like this...