Hit Counter using PHP

Below I give the code for a hit counter in php. Last week I had to come up with a hit counter for a project of mine and I thought of sharing it with you.

It uses a seperate file named ‘counter.dat’ to keep track of the number of visits to your particualr page which you have included this tiny peice of code. Don’t worry about the counter.dat because it will automatically create it for you. Once you get this code you can save it as a seperate php file and then when and where you want it on a page of yours, you just insert an include statement in your particular page and reuse it, the statement is something like this,

include(“yourcounter.php”);

code snippet of ‘yourcounter.php’ is as follows,

<?php
if(file_exists(“counter.dat”))
{
$exist_file = fopen(“counter.dat”, “r”);
$new_count = fgets($exist_file, 255);
$new_count++;

fclose($exist_file);

print(“$new_count people have visited this page”);
$exist_count = fopen(“counter.dat”, “w”);
fputs($exist_count, $new_count);

fclose($exist_count);

}

else
{

$new_file = fopen(“counter.dat”, “w”);
fputs($new_file, “1”);
print(“1 person have visited this page”);
fclose($new_file);

}
?>

Advertisements

One thought on “Hit Counter using PHP

  1. Hey man, I wanted one like this for my blog. I have it in blogspot, do u know where to insert this code in it?? I’m a newbie for this blogging stuff so help is appreciated.
    Nice work!! All the best for the future!!
    Mayura aka podiman.

Comments are closed.