当我在php中将行附加到文件时,前面的行已经被删除,我该如何防止这种情况发生


When I append line to file in php, the previous lines have been deleted, how do I prevent this?

基本上,我只想在文本文件中添加一行,但当我这样做时,它会删除文件中以前的内容。

如何在不删除以前内容的情况下向文本文件中添加一行?

<?php
    $template = $_POST["template"];
    $templateFile = fopen("templates.txt", "a");
    file_put_contents("templates.txt", $template);
    fclose($templateFile);
    //header function to go back to my original page where the form was
?>

如果您使用file_put_contents(),则不需要使用fopen()打开文件,它已经为您做到了:

此函数与依次调用fopen()、fwrite()和fclose()将数据写入文件相同。

此外,您还想设置标志FILE_APPEND,因此您可以附加您的内容,例如

file_put_contents("templates.txt", $template, FILE_APPEND);

您将c风格的fopen fwritefclose与PHP特定的file_put_contents函数混合在一起。你必须选择一个。

使用第一种方法,您必须fopen文件,指定名称和模式,使用fwrite在文件上写入,并使用fclose关闭文件。

或者,您可以使用PHP file_put_contents(实现、文档),正如您所看到的,函数本身会检查文件是否为常规文件,是否未被其他应用程序锁定,写入内容,然后关闭文件。

TL;DR要在PHP中附加到文件,请使用以下代码:

file_put_contents("myfile.txt", "content", FILE_APPEND);

请记住,将postdata写入文件是不安全的!