andresmijares25 andresmijares25 - 2 months ago 16
PHP Question

How to write data to a file with file_put_contents() without overwriting it?

I'm to create a

txt
file with a list of names, those names come from a form.

My logic goes as follows:

if ($_SERVER['REQUEST_METHOD'] == "POST") {
$name = $_POST['username'];
}


function add_name($name, $file_name = "names.txt") {
if(file_exists($file_name)) {
$name = $name;
file_put_contents($file_name, $name);
} else {
$handle = fopen($file_name, 'w+');
fwrite($handle, $name);
fclose($handle);
}
}


Now problem is, it writes the name, however when I set another record, it deletes the previous, any help? maybe
file_put_contents
is not the right function to use?

Answer

If the file already exists, by default file_put_contents() would overwrite the existing file.

To prevent the current file from being overwritten, pass the FILE_APPEND flag as the function's third argument.

For example:

if (file_exists($file_name)) {
    file_put_contents($file_name, $some_value, FILE_APPEND);
} else { 
    //...
}