更新/修改服务器上的现有文件



我想在每个页面加载上添加内容,但是它覆盖文件,而不是更新内容。我的原始代码:

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

我搜索后,找不到解决我的prolem的东西:

如何使用php

编辑/更新TXT文件

php修改文本文件中的一行

我使用了w+r+,但它不起作用。

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

两个都用新内容写文件,而不是保留旧内容。我想保留旧内容,只需将新内容附加到现有文件。

您正在尝试附加到文件,因此您需要模式'a'

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

来自文档:

'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.

最新更新