When a user enters the page in question, a textarea is populated from data from a text file stored on the server. The user can then edit that text (add, erase all or part, and modifiy). When the submit button is clicked, the edited text is written back into the same file from which it came. The code below works. The only problem is that on clicking the submit button, not only is the text saved, but the modifications made by the user disappear from the text box. This givess the user the impression that his/her work in editing the text is gone. Is there any way that the modifications made to the data in the text box can remain after the submit button is clicked?

<body>
<?php $oldtext = file_get_contents('filltext.txt');
?>

<form name="for PHP" method="POST">
<textarea name="PHP_testing" cols="60" rows="10" id="testing">
<?php echo $oldtext;
?>
</textarea>

<input type="submit" name="submit" value="Save Text"/></input> 
</form>

<?php
if(isset($_POST['submit'])){
    $newtext=$_POST['PHP_testing'];
    file_put_contents('filltext.txt',$newtext);
    echo "The modified text has been saved.";
}
?>

</body>

It happens because the POST request write is executed at the end of the script, in practice your write block (file_put_contents()) is placed after the reading block (file_get_contents()), so when a POST request is performed the script:

  1. reads the contents of the file which has not still been modified
  2. it prints the contents to the textarea
  3. and then it saves the input to the file

Move all the PHP logic in top of the file and set only print variables inside the HTML:

<?php

// Initialize
$alert = '';

// Write
if(isset($_POST['submit']))
{
    $newtext = $_POST['PHP_testing']; // <- Sanitize! See filter_input()
    file_put_contents('filltext.txt', $newtext);
    $alert = '<p>The modified text has been saved.</p>';
}

// Read
$oldtext = file_get_contents('filltext.txt');

?>
<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>
<body>

<form name="for PHP" method="POST">
    <textarea name="PHP_testing" cols="60" rows="10" id="testing">
    <?php

    echo $oldtext;

    ?>
    </textarea>
    <input type="submit" name="submit" value="Save Text">
</form>

<?php

echo $alert;

?>

</body>
</html>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.