-3

Hello I have a piece of code that writes to a text file, but I want the php file to completely overwrite the content of the text file, not just add to it, how must I rework my code to make it overwrite instead of just write. this is my code:

    <form name="savefile" method="post" action="">
 <input type="hidden" name="filename" value="code"><br/>
        <textarea rows="40" cols="40" name="textdata" style ="font-family: "Lato", sans-serif;">
        <?php echo file_get_contents('code.txt'); ?>
        </textarea><br/>
        <input type="submit" name="submitsave" value="Save">
</form>
    <?php
    if (isset($_POST)){
        if ($_POST['submitsave'] == "Save"  && !empty($_POST['filename'])) {
            if(!file_exists($_POST['filename'] . ".txt")){
                $file = tmpfile();
            }
            $file = fopen($_POST['filename'] . ".txt","a+");
            while(!feof($file)){
                $old = $old . fgets($file). "|___end message___|___begin message___|";
            }
            $text = $_POST["textdata"];
            file_put_contents($_POST['filename'] . ".txt", $old . $text);
            fclose($file);
        }
        }
    ?>
Rowland Shaw
  • 37,700
  • 14
  • 97
  • 166
parseguy
  • 129
  • 2
  • 17
  • Might wanna check php.net's manual for `fopen();` – Epodax Feb 16 '16 at 12:24
  • You can simply get rid of the entire `$file = fopen($_POST['filename'] . ".txt","a+"); while(!feof($file)){ $old = $old . fgets($file). "|___end message___|___begin message___|"; }` block and then simply `file_put_contents($_POST['filename'] . ".txt", $text);` – Mark Baker Feb 16 '16 at 12:27

1 Answers1

0

Overwrite is nothing but writing a same file, difference is file pointer is at the beginning of the file when you overrite. You can try with mode 'w'. php.net/manual/en/function.fopen.php

Mangesh Sathe
  • 1,987
  • 4
  • 21
  • 40