My website takes in text messages as input, and I want to store these messages in "messages.json" on the server. Every time somebody enters a new message, I simply want to append messages.json with one more entry.
As of now, I can get the user's message ($message) properly sent to "save-message.php", but I couldn't find a way to properly add that $message string into messages.json in the correct format. One issue I was running into when experimenting with json_encode($message) was I could add the elements themselves to the file, but not inside the outer JSON brackets and with a comma after all them except the last one, etc.
Note: If solution requires a call to a JavaScript function, could you show how to adjust the HTML form and the PHP code accordingly to?
Here is my HTML form I am using:
    <form action="/save-message.php" method="POST">
        <textarea name="message" placeholder="Enter your anonymous message here!"></textarea>
        <input id="submitNoteButton" type="submit" value="Submit mystery note"/>
    </form>
</div>
Current save-message.php that can properly save strings to a .txt file:
<?php
    $file = 'messages.txt';
    $message = $_POST['message'];
    file_put_contents($file, $message, FILE_APPEND | LOCK_EX);
    header('Location: /note_submitted.html'); // Redirect
?>
Goal JSON:
 {"messages": [
     {"message":"This is what somebody would enter"},
     {"message":"This is what somebody else would enter"}
 ]}
 
     
    