Non-unique Hit counter in PHP

Non-unique Hit counter in PHP
Non-unique Hit counter in PHP

Title – 51
Non-unique Hit counter in PHP

images-1-300x123-300x1234-300x123

DOC,PDF

-We are going to discuss about how many times the file is opened.
-Here we want to see how many users accessed the file.
-In this topic we are writing a code for counting the number of times the file opened thereby we will know how many were accessed the file.
Here we are using two files,
-A text file to store the count of the file opened
-A php file for writing the code

Program:
<?php
//count.php

function hit_count(){
$filename = ‘count.txt’;
$handle = fopen($filename,’r’);
$current = fread($handle,filesize($filename));
fclose($handle);

$current_inc = $current +1;
$handle = fopen($filename,’w’);
fwrite($handle,$current_inc);
fclose($handle);
}
hit_count();
?>
php51-1-c

Output:
At first the value in the text file is 0.
php51-1-o
When the file is accessed for one time,
Value in the text file: 1
php51-1-o2
When file is accessed for five times,
Value in the text file: 5
php51-1-o3

Here we are checking how many times the file “count.php” is accessed i.e., whenever we are accessing this file we are counting and saving the counted number in “count.txt” file.

So here we have the logic in counting the number of times the file is opened,
-We need a text file (count.txt) saved with 0 as data in it.
-Whenever the file count.php is opened we are opening the count.txt file automatically as we called in php file.
We are reading the content of text file and saving the content into $current variable.
-We had 0 in the file, so $current will hold the value.
Now we are incrementing the value by 1 and again writing that content back into the text file using fwrite() function.
-So if file is opened for one time then the value in the text file is going to be incremented by one.
– Whenever the file is accessed then the count.txt file is opened and incremented by 1.Incremented value is again going to save back into itself.
– We can check the “count.txt” file to know how many times the file is accessed by the users.
-Hence we counted how many times the users accessed the file using the file functions.

images-1-300x123-300x1234-300x123

DOC,PDF

Leave a Reply