Jack Maessen Jack Maessen - 4 months ago 9
PHP Question

how to add value in txt file with php

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

file_put_contents


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);
fclose($fileUserId);


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

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

1||


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

1||2||


But he overwrites the file so it becomes this:

2||


What i am doing wrong?

Answer

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

Note:

'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.

Comments