How to use counter in php page view

This tutorial we are going to implement counter of page view in php. We will create one text file to store data in file. So when we user open website we will increment by one.

Create demo php file

<?php
$handle = fopen("counter.txt", "r"); 
if(!$handle) {
    echo "could not open the file"; 
} else {
    $counter =(int )fread($handle,20);
    fclose($handle); 
    $counter++; 
    echo"Number of visitors to this page so far: ". $counter . "" ; 
    $handle = fopen("counter.txt", "w" ); 
    
    fwrite($handle,$counter);
    fclose ($handle); 
}
?>

You will must require to create counter.txt file in root of the project. fread(file, length) we mention 20 character length to read data from file. $counter++ increase value by 1 and then fopen write the $counter value suppose it 20 and then it write to 21.

Leave a Reply