How to append a line to a file
Short answer
Pass the FILE_APPEND flag to file_put_contents():
<?php
$file = sys_get_temp_dir() . '/recipe-append.txt';
file_put_contents($file, "first\n");
file_put_contents($file, "second\n", FILE_APPEND);
echo file_get_contents($file);Output:
first
secondSeveral processes
If several requests write to the file at once, add a lock:
<?php
$file = sys_get_temp_dir() . '/recipe-append.txt';
file_put_contents($file, '');
foreach (['a', 'b', 'c'] as $line) {
file_put_contents($file, $line . "\n", FILE_APPEND | LOCK_EX);
}
echo count(file($file));Output:
3Without the flag the file is erased
A plain file_put_contents() call replaces the whole contents — make sure the flag is there.
Functions used in this recipe
- file_put_contents — Writes data to a file.
- fopen — Opens a file for reading or writing piece by piece.
- fwrite — Writes a string to an open file.