2

I have a problem with my logs file, in the past, I used fopen($file, "w+"); with the w+ mode to generate and I wrote on the file, and I used fwrite function to write data and header.

With the time I changed the mode to fopen($file, "a"); and I use the fputs function to write the header, and fwrite for writing the data, but right after that the size of logs is being Vvery small compared to old files, and I think that I lose the data.

My question: I think that the write mode, block the code (sometimes) to write on the file, is that can be true? if not, are there any other things I need to check to fix the problem?

Past code :

if (file_exists($file)) {
    $handle = fopen($file, "a+");
    fwrite($handle, $record);
    fclose($handle);
} else {
    $handle = fopen($file, "w+");
    $header = 'Name;Last Name;Age;User;Comment';
    fwrite($handle, $header);
    fwrite($handle, $record);
    fclose($handle);
}

New Code :

if(!file_exists($file)) {
    $handle = fopen($file, 'a');
    $headers = ['Name', 'Last Name', 'Age', 'User', 'Comment'];
    fputs($handle, implode($headers, ';')."\n");
    fwrite($handle, $record);
    fclose($handle);
} else {
    $handle = fopen($file, "a+");
    fwrite($handle, $record);
    fclose($handle);
}

Example: On the past, the size of a day file is 71Mo, but right after the modifications the size of day file was 7Ko

sayou
  • 893
  • 8
  • 29
  • Out of interest what OS are you using – RiggsFolly Dec 09 '19 at 18:06
  • Also a [Minimal, Complete and Verifiable Example](http://stackoverflow.com/help/mcve) would help us to help you – RiggsFolly Dec 09 '19 at 18:07
  • _Small Point_ `fputs — Alias of fwrite()` – RiggsFolly Dec 09 '19 at 18:13
  • @RiggsFolly I added some code to understand more the issue – sayou Dec 10 '19 at 07:46
  • 1) you dont need to worry if the file exists or not. The `a` mode creates the file if the file does not exist. 2) You need to see if anything is missing from the file, as there could be 1000 reasons why there is less data in it now!! – RiggsFolly Dec 10 '19 at 09:09
  • For the first answer, I check if the file exists just to create it and add the header on the top of the file, for the second answer, can you please give me the correct way to check where's the isssue ? – sayou Dec 10 '19 at 09:33
  • I cannot see where the issue is. When I try to test this concept there is no issue. As you say it is working, but there is just less data in the file, so maybe you have less visitors, or less of whatever activity this is logging – RiggsFolly Dec 10 '19 at 09:42

0 Answers0