hazz995 Posted February 1, 2010 Share Posted February 1, 2010 I tried writing to a file, all existing code gets deleted. I tried appending but that only adds to the end of the file. How can I add to the start of the file without deleting the existing contents? Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/190494-writing-to-file/ Share on other sites More sharing options...
teamatomic Posted February 1, 2010 Share Posted February 1, 2010 rewind($fh); fwrite($fh, "$new_contents"); HTH Teamatomic Quote Link to comment https://forums.phpfreaks.com/topic/190494-writing-to-file/#findComment-1004814 Share on other sites More sharing options...
hazz995 Posted February 1, 2010 Author Share Posted February 1, 2010 rewind($fh); fwrite($fh, "$new_contents"); I've got it to write at the start of the file thanks to rewind but still one problem, if I open the file with r+ it overwrites existing data as it goes along instead of just nicely writing text at the start of the file without deleting anything. Start: existing text Run code: (inserting the text "hello" at the start) helloing text What I'm trying to achieve: helloexisting text I tried changing the r+ to w but that just wipes everything when writing. $string = "test text"; $fp = fopen("test.php", 'r+'); rewind($fp); fwrite($fp, $string); fclose($fp); Quote Link to comment https://forums.phpfreaks.com/topic/190494-writing-to-file/#findComment-1004830 Share on other sites More sharing options...
teamatomic Posted February 1, 2010 Share Posted February 1, 2010 rewind() resets the pointer to the beginning of the file. To write a new line you need to add the \n at the end of the line, else it overwrite the bytes. To do what you want you need to read the file into a string then just concatenate it to your new string and rewrite it to file. <?php $string = "test"; $file = file_get_contents("./links.txt"); $string .= "$file"; file_put_contents("./links.txt", "$string"); ?> HTH Teamatomic Quote Link to comment https://forums.phpfreaks.com/topic/190494-writing-to-file/#findComment-1004836 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.