write to a file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
yaron
Forum Contributor
Posts: 157
Joined: Fri Aug 22, 2003 8:40 am

write to a file

Post 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?
User avatar
Crashin
Forum Contributor
Posts: 223
Joined: Mon May 06, 2002 3:42 pm
Location: Colorado

Post 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.
:)
User avatar
vigge89
Forum Regular
Posts: 875
Joined: Wed Jul 30, 2003 3:29 am
Location: Sweden

Post 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

?>
Post Reply