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?
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.
You can as well do it differently. The commented code below illustrates how:
<?php
$txtFile = __DIR__ . "/fileUserId.txt";
$UserID = 9; //<== THIS VALUE IS FOR TESTING PURPOSES,
//<== YOU SHOULD HAVE ACCESS TO THE ORIGINAL $UserID;
//CHECK THAT THE FILE EXISTS AT ALL
if( file_exists($txtFile) ){
// GET THE CONTENTS OF THE FILE... & STORE IT AS A STRING IN A VARIABLE
$fileData = file_get_contents($txtFile);
// SPLIT THE ENTRIES BY THE DELIMITER (||)
$arrEntries = preg_split("#\|\|#", $fileData);
// ADD THE CURRENT $UserID TO THE $arrEntries ARRAY
$arrEntries[] = $UserID;
// RE-CONVERT THE ARRAY TO A STRING...
$strData = implode("||", $arrEntries);
// SAVE THE TEXT FILE BACK AGAIN...
file_put_contents($txtFile, $strData);
}else{
// IF FILE DOES NOT EXIST ALREADY, SIMPLY CREATE IT
// AND ADD THE CURRENT $UserID AS THE FIRST ENTRY...
file_put_contents($txtFile, $UserID);
}