function that adds lines to the top of the file this function adds 1 line to the bottom of the file $gbfile='gb.txt'; function add($str){ global $gbfile; $tmp = trim($str); $fp=fopen($gbfile,'a+'); flock($fp, LOCK_EX); fwrite($fp, $tmp. "\n"); flock($fp, LOCK_UN); fclose($fp); } I want to write a function (exactly like above), but that adds lines to the top of the file. If simply replace a+ with r+ in $fp=fopen($gbfile,'a+') it won't be the same because of "\n" in fwrite($fp, $tmp. "\n"); . Can somebody write such function? What is . (point) in fwrite($fp, $tmp. "\n"); ?
The only way I have been able to accomplish this is the read the file into memory, prepend the lines of text, and replace the file with the new contents. This is the same approach you would use if you are editing text within the file -- read, change in memory, overwrite the file. I should add that there are not many times when you want to do this. It will result in lots of extra disc writing activity and, as the file grows in size, it will slow your machine. The file needs to be rarely used. If it is a log, for instance, you should always append lines to the end of the file. If you want to display the contents of the file in reverse order, do an in memory reverse sort of the lines. If it is an html file, you are better separating the header from the content of the file so that you can change the look and feel opf your website without needing to change all the pages.