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

Asked

Viewed 82 times

1

Good,

I am creating a Function that will create a new log.txt, if you already exist just write the new data.

But it is giving errors, since I am testing, and I click REFRESH to the browser it just 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...?

  • Did I get my answer, friend? That’s right?

  • Hello Snoopy12, I know you are not obliged to evaluate my answer. But take into account that no one at Sopt is required to answer questions either. And what drives us to do this is the reward given to us by the "Builders". If there is an error in my answer, share it with me! Even if you didn’t like my answer, my didactics or my "aproach". Any questions are available.

1 answer

0

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

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

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

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

Another thing, using the mode a you do not need to verify that the file exists. Because if there is no command itself it will create it. So this piece of code is not necessary:

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 on documentation

  • If the folder does not exist, it will create ? ?

  • @Pedroaugusto no... Create only the archive. The "file" he says is an archive. He’s probably from portugal. https://www.dicionarioinformal.com.br/significado/ficheiro/5174/

  • 1

    If he wants to create the folders, just use mkdir(dirname('inc/logs/log1.txt'), true);

  • @Valdeirpsr.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.