Page 1 of 1
write to a file
Posted: Fri Dec 19, 2003 9:39 am
by yaron
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?
Posted: Fri Dec 19, 2003 10:23 am
by Crashin
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.

Posted: Fri Dec 19, 2003 11:15 am
by vigge89
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
?>