0

I want to add content to file on every page load, but it overwrite file, not updating content. my original code:

$file_handle = fopen('log.txt', 'w'); 
fwrite($file_handle, $message);
fclose($file_handle);

After i searching, nothing found to solve my prolem:

How to edit/update a txt file with php

PHP Modify a single line in a text file

I used w+ and r+ but it didn't work.

$file_handle = fopen('log.txt', 'w+'); 
fwrite($file_handle, $message);
fclose($file_handle);

Both write file with new content, not keep old contents. I want to keep old contents, just append new content to existing file.

Padideh
  • 139
  • 2
  • 13

1 Answers1

2

You are trying to append to a file so you need the mode 'a':

$file_handle = fopen('log.txt', 'a'); 
fwrite($file_handle, $message);
fclose($file_handle);

From the docs:

'a': Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended.

WayneC
  • 5,569
  • 2
  • 32
  • 43