Appending adds new text after the existing file content.

append `FILE_APPEND` keeps previous content and adds the next string at the end.

Append File

line
append_file.php
Replay: real traced execution (multi-file project)
<?php
$line = "second";
$file = "php_append_file.txt";

file_put_contents($file, "first\n");
file_put_contents($file, $line . "\n", FILE_APPEND);
$content = trim(file_get_contents($file));
unlink($file);

echo "line=" . $line . "\n";
echo "content=" . str_replace("\n", "|", $content) . "\n";
<?php
$line = "third";
$file = "php_append_file.txt";

file_put_contents($file, "first\n");
file_put_contents($file, $line . "\n", FILE_APPEND);
$content = trim(file_get_contents($file));
unlink($file);

echo "line=" . $line . "\n";
echo "content=" . str_replace("\n", "|", $content) . "\n";
<?php
$line = "final";
$file = "php_append_file.txt";

file_put_contents($file, "first\n");
file_put_contents($file, $line . "\n", FILE_APPEND);
$content = trim(file_get_contents($file));
unlink($file);

echo "line=" . $line . "\n";
echo "content=" . str_replace("\n", "|", $content) . "\n";
  1. $line ← second, $file ← php_append_file.txt, $content ← first second

    1<?php2$line→ second = "second"; //@line="third", "final"3$file→ php_append_file.txt = "php_append_file.txt";45file_put_contents($filephp_append_file.txt, "first\n");6file_put_contents($filephp_append_file.txt, $linesecond . "\n", FILE_APPEND);7$content→ first
    second = trim(file_get_contents($filephp_append_file.txt));8unlink($filephp_append_file.txt);910echo "line=" . $linesecond . "\n";11echo "content=" . str_replace("\n", "|", $contentfirst
    second) . "\n";
    outputline=second
    content=first|second
  1. $line ← third, $file ← php_append_file.txt, $content ← first third

    1<?php2$line→ third = "third";3$file→ php_append_file.txt = "php_append_file.txt";45file_put_contents($filephp_append_file.txt, "first\n");6file_put_contents($filephp_append_file.txt, $linethird . "\n", FILE_APPEND);7$content→ first
    third = trim(file_get_contents($filephp_append_file.txt));8unlink($filephp_append_file.txt);910echo "line=" . $linethird . "\n";11echo "content=" . str_replace("\n", "|", $contentfirst
    third) . "\n";
    outputline=third
    content=first|third
  1. $line ← final, $file ← php_append_file.txt, $content ← first final

    1<?php2$line→ final = "final";3$file→ php_append_file.txt = "php_append_file.txt";45file_put_contents($filephp_append_file.txt, "first\n");6file_put_contents($filephp_append_file.txt, $linefinal . "\n", FILE_APPEND);7$content→ first
    final = trim(file_get_contents($filephp_append_file.txt));8unlink($filephp_append_file.txt);910echo "line=" . $linefinal . "\n";11echo "content=" . str_replace("\n", "|", $contentfirst
    final) . "\n";
    outputline=final
    content=first|final