Well this is as simple as it gets. The very basic tutorial of making your own web hits counter in PHP.
I will just use flat file database so no MySQL is involved. After that I will also use MySQL in second part so that you can understand how MySQL one would work.
First of all create a PHP file called counter.php and also create a file called hits.php
Put the following code in counter.php
$fd = fopen( ‘hits.php’, ‘r’ ); // Opens the file to read the data.
while( ! feof( $fd ) )
$tmp = fgets( $fd ); //Gets the data i.e. number of hits into tmp variable.
$tmp = $tmp + 1; //Increases the counter by 1.
fclose( $fd ); //Closes the file that was opened for reading.
$fd = fopen( ‘hits.php’, ‘w’ ); //Opens the file for writing.
fputs( $fd, $tmp ); //Writes the data.
fclose( $fd ); //Closes the file.
I have made it simple one so that both read and write file functions are used.
Make sure that the counter.php and hits.php are in same folder. All you need to do now is CHMOD hits.php
Wherever you want to use or place this counter on your website all you need to do is add the code below in the .php file of your site.