PageStat Blog » News, Nonsense, Software

Text Hit Counter in PHP

PHP Flat File Counter

PHP Flat File Counter

In this article we’ll show you how to make a hit counter in PHP. You can use built in PHP functions to edit a .txt file and count page views or hits relatively easy. This tutorial will walk you through those steps and we’ll even attach a Zip file with the code below.

If you want something more advanced we’ll also show you how to do it using a MySQL database, but we’ll do that in another post. So here we go…

I always hate trying to search and find tutorial solutions zipped up,
so >>>DOWNLOAD THE SOLUTION HERE<<<

The directions are simple.

Copy and paste the code below into any page you want to count hits on and then save the file.
<?php
//make sure the hits.txt file is in the same folder
//make sure that the file is writable
$hits = “hits.txt”;
if(file_exists($hits)){
$var = fopen( $hits,’r+’);
$visits = fread($var,filesize($hits));
rewind( $var );
$visits++;
if ($visits == 0){
$visits = 1;
}
fwrite($var, $visits);
fclose($var);
echo number_format($visits);
}
else{
echo “Create a file named hits.txt in this directory and make sure to chmod it to 755”;
}
?>

Then Upload the hits.txt file into the same directory. Make sure the file is writable try 755 and if not 777.

If you have questions go here
http://pagestat.com/blog/2010/07/13/hit-counter-in-php/

If you want an even simpler alternative then use our Page Hit Counter it’s a simple html copy and paste script that places and image counter on any page you want. No registration required.

Post any questions you may have and i’ll gladly answer them.