Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a new and appending a file in PHP without erasing contents

Tags:

php

fwrite

How could one write a new line to a file in php without erasing all the other contents of the file?

<?php
if(isset($_POST['songName'])){

        $newLine = "\n";
        $songName = $_POST['songName'];
        $filename = fopen('song_name.txt', "wb");
        fwrite($filename, $songName.$newLine);
        fclose($filename);
    };

?>

This is what the file looks like Current view

This is what is should look like Ideal View

like image 721
John Smith Avatar asked Dec 19 '22 14:12

John Smith


2 Answers

Simply:

file_put_contents($filename,$songName.$newLine,FILE_APPEND);

Takes care of opening, writing to, and closing the file. It will even create the file if needed! (see docs)

If your new lines aren't working, the issue is with your $newLine variable, not the file append operations. One of the following will work:

$newLine = PHP_EOL;  << or >>  $newLine = "\r\n";
like image 183
BeetleJuice Avatar answered May 04 '23 08:05

BeetleJuice


You have it set for writing with the option w which erases the data.

You need to "append" the data like this:

$filename = fopen('song_name.txt', "a");

For a complete explanation of what all options do, read here.

like image 45
Robert Rocha Avatar answered May 04 '23 09:05

Robert Rocha