tomcommathe Posted November 16, 2008 Share Posted November 16, 2008 Title kind of says it all, I am new to PHP and I am trying to creating a little text area input box that when you click submit the *.txt file doesn't get overwritten and the new information is placed at the top of the file. The Write Code: <?php if (isset($_POST['submit'])) { $filename = "name.txt"; $open = fopen($filename, "r+"); $name = $_POST['name']; $sayWhat = $_POST['sayWhat']; $hidden = $_POST['hidden']; fwrite($open, "Name:\t$name <br />"); fwrite($open, "What?!:\n $sayWhat \n"); fwrite($open, "$hidden\r <br>"); fclose($open); } ?> The Display Code: <? $filename = "name.txt"; $fp=fopen($filename,'r'); $content=fread($fp,filesize($filename)); fclose($fp); $content = $content; echo $content; ?> The test page, don't mind the shitty layout I am working on that too: http://mopedstl.com/phpTest/test2.php Link to comment https://forums.phpfreaks.com/topic/132950-write-to-the-top-of-a-txt-file-no-over-writes/ Share on other sites More sharing options...
bobbinsbro Posted November 16, 2008 Share Posted November 16, 2008 <?php if (isset($_POST['submit'])) { $filename = "name.txt"; $open = fopen($filename, "r+"); $content = fread($fp,filesize($filename)); $newContent = "Name:\t$name <br />"; $newContent .= "What?!:\n $sayWhat \n"; $newContent .= "$hidden\r <br>"; $newContent .= $content; fwrite($open, $newContent); fclose($open); ?> Link to comment https://forums.phpfreaks.com/topic/132950-write-to-the-top-of-a-txt-file-no-over-writes/#findComment-691361 Share on other sites More sharing options...
PFMaBiSmAd Posted November 16, 2008 Share Posted November 16, 2008 There are two ways to do this (well actually three if you consider storing the information in a database so that you can retrieve it in any order you want.) 1) The easy way - write (append) the new information to the end of the file and reverse the order when you display it. To display the information, use the file() function to read the lines into an array and use the array_reverse() function to reverse the order. 2a) The hard way, without any failsafe file error recovery - read the existing file using the method of your choice. Recreate the file and write the new content, followed by the old content. 2b) The hard way, with failsafe file error recovery - write the new content to a temporary file, then read and append the existing content to the temporary file. After the temporary file has been written and closed without any errors, delete the old file and rename the temporary file to be the actual file in use. Link to comment https://forums.phpfreaks.com/topic/132950-write-to-the-top-of-a-txt-file-no-over-writes/#findComment-691367 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.