Hello all,
I want to write to a begining of a file witout overwriting anything that is already there.
I'm using r+ in the fopen function but it over writing my previous file (up to the number of new lines I'm writing).
Any way around it?
write to a file
Moderator: General Moderators
See http://www.php.net/manual/en/function.fwrite.php

[[Editors note: There is no "prepend" mode, you must essentially rewrite the entire file after prepending contents to a string. Perhaps you will use file(), modify, implode(), then fopen()/fwrite() it back]]
To put strings into the front of the file, you need to set place the pointer at the top of the file when openning the file with fopen(), see fopen() for more info.
here's a script for it:
Code: Select all
<?php
$filename = "test.txt";
$new = "something";
// Open file and read contents
$fp = fopen ($filename, "r"); //Open file for reading
$oldcontents = fread($fp, filesize($filename));
fclose ($fp); //Close file
$fp = fopen ($filename, "w"); //Open file for writing
$newcontent = "$new.$oldcontents;
fwrite ($fp, $newcontent);
fclose ($fp); //Close file
?>