Monday 12 April 2010

Hit Counter Project Using PHP

Today hit counters play a very important role in website. It is used for displaying the count of hits a specific website or webpage get in its lifetime. So visitor can see how many hits a page get.

Here is a simple script which you can use for basic hit counter project..

<?php
$filename = "counter.hits" ;
$startdate = "December 2002" ;
$ip = getenv("REMOTE_ADDR") ;
$currentip = "$ip";
$file = file($filename);
$file = array_unique($file);
/*
This is the guts of the counter
*/
$file = "$filename";
$fd = fopen ($file,"r");
$fget= fread ($fd,filesize ($file));
fclose ($fd);
$totalips = htmlspecialchars($fget);
if (preg_match ("/$ip/i","$totalips"))
{$file = file($filename);
$file = array_unique($file);
$pagehits = count($file);
echo "Total hits,
";
echo "$startdate: 000$hits";}
else
{
$fd = fopen ($filename,"r");
$fstring = fread ($fd,filesize ($filename)) ;
fclose($fd) ;
$fd = fopen ($filename,"w");
$fcounted = $fstring.$currentip."n";
$fout= fwrite ($fd,$fcounted);
fclose($fd);
$file = file($filename);
$file = array_unique($file);
$pagehits = count($file);
echo "Total hits,
";
echo "$startdate: 000$hits";
}
?>


Learn, Create and enjoy this project.