PHP page hits counter script using text fileWe 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
this script.
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...
|