Sunday, June 23, 2013

Non-database page views counter using PHP

Page views counter is very helpful to get numbers of visitors visiting your website, but most of time many people saves that in database and in text files. In this tutorials we are going to save it in text files.

function hits(){
$ips = Array("");     //Enter ip address which you don't want count
$file = "hits.txt"; //file name
$ip = $_SERVER["REMOTE_ADDR"];     //getting ip address
if($ips[0]!=$ip){     //checking that 'ips' are not matched with var 'ip'
if(file_exists($file)){      //checking for hits.txt exists or not
$fr = fopen($file, "r");     //Opening file for reading
$fre = fread($fr, filesize($file))+1;      //reading and incrementing 1 
$fh = fopen($file, "w");      //Opening file for writing
$fw = fwrite($fh, $fre);     //writing
}elseif(!file_exists($file)){      //if not exists var 'hits.txt' then to create one 
$fh = fopen($file, "w");     //opening file for writing
$fw = fwrite($fh, "0");     //writing 0 to start from zero
echo "File Created.";     //displaying a positive message
hits();    // calling our function

The ideal way to use this script is not to make the numbers of hits visible to your users, but if you want so make it visible then read the file and print it.

Add this block of code after calling the function 'hits()'.
$fr = fopen("hits.txt", "r");    //open file to read
$read = fread($fr, filesize("hits.txt"));   //read the file
echo "Total Views: ".$read; // print the contents of file 'hits.txt'

1 comment:

Your Comment Will Be Visible After Approval, Thanks !