andresmijares25 andresmijares25 - 1 year ago 83
PHP Question

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

I'm to create a

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

My logic goes as follows:

$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);

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

Answer Source

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 { 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download