Simple Text File Based PHP Hit Counter

by Hiroshi on June 13, 2008

in Hit Counter II, No Database

We can create a quick simple text based hit counter for any webpage or website and there is no database requirement for that.

You will be needing two files for that.

1- one blank text file
2- PHP code file

Remember when you will upload the text file, make sure its properties are set to write (CHMOD must be set to 777. If you do it through your favorite FTP software then just right click at file and click properties/CHMOD and write in permissions box 777 or check all boxes of owner, group and public. Because we have to write in that file and file will be updated so we need write permissions at that text file)

Usage (Code)

if (file_exists('count_file.txt'))
$fil = fopen('count_file.txt', r);
$dat = fread($fil, filesize('count_file.txt'));
echo $dat+1;
$fil = fopen('count_file.txt', w);
fwrite($fil, $dat+1);
$fil = fopen('count_file.txt', w);
fwrite($fil, 1);
echo '1';

While text file (count_file.txt) will just contain any number i.e. 1 or 200 or as you like from where your count must start. Put above script in your php file where you want the text counter to appear and upload a text file with some number in it i.e. 1, in the same directory.

You are done. When ever that page will be viewed PHP script will be executed, If text file exists it will open the text file, read it, update it and increment its number by 1 i.e. it will add 1 in number present in the text file and close it. If text file does not exist, it will create a text file in the same directory and add a number ‘1’ in it. And the process goes on. You do not need to have a database for this counter.

Download PHP Text counter

Related Posts

Previous post:

Next post: