Search code examples
phpfopenfwritefclose

How to add new data to the top of .txt without deleting in PHP


When I use this codes

$fp = fopen('data.txt', 'w');
fwrite($fp, $data);
fclose($fp);

It overwrites the text. I want the old data too at footer. so, how to add new data to the top of .txt without deleting in PHP

Possible output.txt and view

(new) line8
(new) line7
(new) line6
(old) line5
(old) line4
(old) line3
(old) line2
(old) line1

Solution

  • $txt = "col1 col2 col3 coln";
    file_put_contents('data.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
    

    Please, try this. Thanks