View Full Version : add line of text to beginning of file

03-24-2004, 11:47 PM
How do you add a line of text to the beginning of a file? I'm able to put it at the end of the file, but i need the new line at the beginning.


03-25-2004, 12:28 AM
$file = 'locationOfFile';

$array = file($file);

$str = "new text";

for ($i = 0; $i<count($array); $i++) {

$str .= $array[$i];


$fp = fopen($file, "w+");
fwrite($fp, $str);

Didn't test it... so something like that...

03-25-2004, 03:20 PM
you were possibly using a instead of w

$fp = fopen($file, "w+");

the w+ writed to the start of a file and if not available then it creates, whereas a+ points to the end of the file

03-25-2004, 04:16 PM
nooooooooo ;) w+ will delete the contents of the file if exists , else create a new file.

You can't actually write to the beginning of a file as such , you can open a file and fseek() to the beginning of the file , but you will be overwriting the existing data at that part of the file.

duniyadnd 's example is a typical workaround , read the file into memory , add your data and re-save.

03-25-2004, 10:18 PM
Thanks, that's what i figured. The reason I originally asked was because I was trying to code my own blog, but I went instead with WordPress, so it doesn't matter anymore. Thanks for the info tho, I'm sure I'll use it in the future.


EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum