The code that would be handled by a counter whose value would be recorded in the file would be this:
Source: This Stackoverflow response in English
$file="visitas.txt";
// Abrir el archivo para lectura
$fp = fopen($file, "r");
// Obtener el valor actual
$count = fread($fp, 1024);
// Cerrar el archivo
fclose($fp);
// Agregar 1 al valor actual
$count = $count + 1;
// Actualizar el valor en el archivo
$fp = fopen($file, "w");
fwrite($fp, $count);
// Cerrar el archivo
fclose($fp);
// Mostrar el total de visitas, si fuera necesario
echo "<p>Total de vistas: " . $count . "</p>";
There are other techniques, but in these cases a total number of visits is not saved in the file. What these techniques do is save the total number of visits in the file size!
Source of both methods: This Stackoverflow response in English
1. Increasing the file size by each visit:
$file="visitas.txt";
$fp = fopen($file, "r+");
while(!flock($fp, LOCK_EX)) { // da acceso exclusivo al archivo
//Espera mientras ocurre el bloqueo
}
$counter = intval(fread($fp, filesize($file)));
$counter++;
ftruncate($fp, 0); // trunca el archivo
fwrite($fp, $counter); // escribe el dato
fflush($fp); // flush de la salida antes de quitar el bloqueo
flock($fp, LOCK_UN); // quita el bloqueo
fclose($fp);
2. Writing a 1
in the file each time there is a visit:
There is another similar method, which writes a 1
each time a visit occurs and like the previous one, the total visits are calculated based on the size in bytes of the file:
file_put_contents( $file, '1', FILE_APPEND|LOCK_EX );
// Muestra el total de visitas si fuera necesario
echo "Total de visitas: ".filesize($file);
In this case, your file will be filled with 1
, as they visit the site. When there are a million visits there will be 1 million 1
and the file size will be 1 million bytes.
Here we have it with 16 visits: