Jack Maessen Jack Maessen - 1 year ago 55
PHP Question

how to add value in txt file with php

I want to add a value (not overwrite!) to a txt file with


This is what i have so far:

$fileUserId = fopen("fileUserId.txt", "w") or die("Unable to open file!");
$UserIdtxt = $UserID."||";
file_put_contents("fileUserId.txt", $UserIdtxt, FILE_APPEND);

is an integer, like 1, 2, 3 etc.

So when the the UserID is 1, the fileUserId.txt looks like this:


When there is another user with ID 2,
the fileUserId.txt should look like this:


But he overwrites the file so it becomes this:


What i am doing wrong?

Answer Source

Remove the fopen and fclose line and you are fine. file_put_contents does this internally. And fopen("fileUserId.txt", "w") clears the file.


'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download