Jump to content

[SOLVED] is it possible to append at beginning of a file


abdfahim

Recommended Posts

In the sense your thinking of...no (say that since we've all been there ;))

 

Your gonna have to read your file into a variable. Set another var with the content you'd like at the beginning of your file, and concantenate them together, then rewrite the file.

 

$old_file = file_get_contents(...);

$new_stuff = '...';

 

$file = $new_stuff . "\n" . $old_file;

 

//rewrite the file

 

best we get for flat files, but that goes for most scripting languages. Even if there is some magic function in other languages, this is probably the process when you get down to the meat and potatoes.

 

beaten to it again...gotta stop being so longwinded ;)

If your file could grow to be bigger than the available memory, then you would need to read/write smaller blocks.

 

In a real world application, you would actually create a new temporary output file, write the new content to the beginning, then read blocks of your existing file and write it to the new file. Then after you have successfully written to the temporary output file, delete your old original file and rename the temporary output file to be the new actual file.

 

If there is a chance of multiple concurrent access, you would need to use file locking to prevent loss of data.

 

If this is something like a blog or an article site were you are doing this to put newer content at the start of a file so it is output first, you seriously need to consider using a database as it avoids all the problems of getting the data in the order you want and concurrent updates/file locking issues.

  • 2 weeks later...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.