Pages

How to make a Hit Counter using PHP

Hello all! in this post i m going to show you how to make a web hit counter using PHP.It is a very easy and useful hit counter which can display the total number of visits made to your website.In this post you will also learn the file handling capabilities of PHP.Following is the complete code of counter.The file counter.dat is already created on the server, than this file is read and incremented everytime your webpage is requested by a browser.

<?php
$file= "counter.dat" ;
$fileData = fopen ($file , "r") or exit("Unable to Open file") ;
$visits = fread ($fileData , filesize ($file)) ;
echo "<table border='1' >";
echo "<tr bgcolor='cyan' align='center'><td>My Hit Counter</td></tr>";
echo "<tr bgcolor='blue' align='center'><td><font color='white'>".$visits."</font></td></tr>" ;
echo "</table>";
fclose($fileData) ;
$fileData = fopen ($file , "w") or exit("Unable to Open file.") ;
$incrementVisit = $visits + 1 ;
$fsent= fwrite ($fileData , $incrementVisit ) ;
fclose($fileData) ;
?>

In the first line the $file variable is holding the filename.This file is than opened in read mode by the fopen() function along with "r" attribute.The data is read and later incremented by the fwrite() function.

 

0 comments:

Post a Comment