A.B.C.

You are here: Home > Web Dev > Add a PHP counter

Add a PHP counter

An easy way to add a visit counter on your webpage, is by using this php code:

<?php
$monfichier = fopen('compteur.txt', 'r+');
$pages_vues = fgets($monfichier); // On lit la première ligne (nombre de pages vues)
$pages_vues++; // On augmente de 1 ce nombre de pages vues
fseek($monfichier, 0); // On remet le curseur au début du fichier
fputs($monfichier, $pages_vues); // On écrit le nouveau nombre de pages vues
fclose($monfichier);
//echo 'Cette page a été vue ' . $pages_vues . ' fois !';
?>

For this to work, you need a text file, named compteur.txt, at the same location as the html/php file. At start, this text file contains 1.

Each time the webpage is opened, the following happens:

  • open the file
  • read the file content
  • add 1 to the number
  • store the new number to the file
  • close the file

 

nach oben