Image based hit counter in PHP to keep track of visitor.
Here we are going to design simple image based hit counter to keep track of visitor. We are going to keep record in a text file so we do need any kind of database. We are going to keep whole record in counter.txt file. In the same directory where you putting the PHP file for this counter, create a file 'counter.txt' and CHMOD it to 0777. Initially put 0 in it and save the file. As this counter is image based we are putting our Image in "imgs" folder.Click here for live Demo
Fetching Data
Now we have process data using PHP to track count. PHP provides fopen () function. The formal syntax of the fopen() function is as follows:fopen(string $filename, string $mode [, boolean $use_include_path ])
$filename represents the filename to open, $mode represents the "mode" under which the fopen() function is opening the file (see Table 1), and $use_include_path is a Boolean value that indicates whether the file should be looked for in the PHP include path. The fopen() function then returns a "reference" to the opened file, which is used when working with other file system functions, or returns false if the fopen() call fails.
| Table 1 Modes supported by fopen() | |
| r | Open the file for reading. |
| r+ | Open the file for reading and writing. |
| w | Open the file for writing, overwriting existing files, and creating the file if it does not exist. |
| w+ | Open the file for reading and writing, overwriting existing files, and creating the file if it does not exist. |
| a | Open the file for writing, creating the file if it does not exist, and appending to the file if it does. |
| a+ | Open the file for reading and writing, creating the file if it does not exist, and appending to the file if it does. |
| b | Open the file in binary reading/writing mode (applicable only on Windows systems; however, recommended in all scripts). |
Open file to get counter value. And store count in variable and closed the file.
//Opening file to get counter value $fp = fopen ("counter.txt", "r");
$count_number = fread ($fp, filesize ("counter.txt"));
fclose($fp);
Processing Data
We have count value now going to process and display count with the help of images in “imgs” folder. This script increment a hits count every time it is called and new count get stored in file.
<?php
$i="";
$ImgPath="imgs/"; //Path of image folder
$counter = (int)($count_number) + 1;
$count_number = (string)($counter);
$len = strlen($count_number);
while($len!=$i && $len!=0)
{
echo "<img src="/.$ImgPath.$count_number[$i].".jpg alt=\"You are visitor number $count_number\" width=20 Height=22>";
$i++;
}
$fp = fopen ("counter.txt", "w");
fwrite ($fp, $count_number);
fclose($fp);
?>
Download Source Code
Download Source code for 'Image based hit counter in PHP to keep track of visitor'Download

written by Unreal Media, November 08, 2008









