php - create txt file and add all new records in it

1

Good,

I'm creating a function that will create a new log.txt, if already exist just write the new data.

But it is giving errors, since I am testing, and I click REFRESH to the browser it only did this.

 ficheiro log.txt \
 ola
 /n

I wanted to fix the problems and add more security in the files

$path_log = 'inc/logs/log1.txt'; 
$log_msg = 'ola'. PHP_EOL;
log_editor($path_log, $log_msg);

function log_editor($path_log, $log_msg) {

   $Handle = fopen($path_log, 'wb');

   if (file_exists($path_log)) {    

    fwrite($Handle, $log_msg. '\n');
    //file_put_contents($file, $contents);
    fclose($Handle);        

   } else {

    fwrite($Handle, $log_msg);
    fclose($Handle);         
   }     
}

Where am I going wrong ...?

    
asked by anonymous 09.08.2018 / 03:12

1 answer

0

You are always putting the file pointer at startup using mode w . In this way, he will always write on top of what has already been written.

To write at the end of the file, you need to use a . So:

$Handle = fopen($path_log, 'a');

This way it will start typing at the end of the file.

Another thing, using mode a you do not need to check if the file exists. For if there is not the command itself will create it. Soon this piece of code is not needed:

if (file_exists($path_log))...   

So, I would leave the code like this:

$path_log = 'inc/logs/log1.txt'; 
$log_msg = 'ola'. PHP_EOL;
log_editor($path_log, $log_msg);

function log_editor($path_log, $log_msg) {

   $Handle = fopen($path_log, 'ab');

   fwrite($Handle, $log_msg);
   fclose($Handle);

}

See more at documentation

    
09.08.2018 / 03:45