Reading and writing in a file with PHP

1

Good I have a doubt about the edition of a text file, it turns out that by default we have visits.txt with the value 0.

Every time we update the PHP program, you have to increase this value by 1 and visualize it on the screen.

I thought of the following code.

<?php
   $f1 = 'visitas.txt';
   $counter = file_get_contents($f1);
   echo 'Esta es la visita número '.++$counter;
   $h1 = fopen($f1, 'w');
   fwrite($h1, $counter);
   fclose($h1);
?>

The problem is that they ask me to open both the write and read file in the fopen and update the value from 0 and also show it on the screen. Any ideas to do it without using the file_get_contents?

Thanks in advance.

    
asked by Vasyl Havrylyuk 25.10.2018 в 12:06
source

1 answer

0

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:

    
answered by 25.10.2018 / 13:47
source