Write to Beginning of 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
Toot4fun
Forum Commoner
Posts: 25
Joined: Wed Dec 10, 2003 11:44 am

Write to Beginning of File

Post by Toot4fun »

I have an error log where I'd like to write the latest entry to the top of the file rather than the bottom. Is this possible to do? If so, how is it done?

Thanks.
User avatar
Nathaniel
Forum Contributor
Posts: 396
Joined: Wed Aug 31, 2005 5:58 pm
Location: Arkansas, USA

Post by Nathaniel »

fopen your error log using mode 'r+', "Open for reading and writing; place the file pointer at the beginning of the file."
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Note that writing data immediately after opening the file in Nathaniel's method will overwrite data in the file already. This is likely not the wanted effect. The only way to effectively do this is loading the file data into a variable, prepending the information and write the entire file back again. Not fun, but that's the nature of linear files.
litebearer
Forum Contributor
Posts: 194
Joined: Sat Mar 27, 2004 5:54 am

Post by litebearer »

A quick funtion to accomplish your task..

Code: Select all

function write_beg($filename, $data)
{
  //Imports old data
  $handle = fopen($filename, "r");
  $old_content = fread($handle, filesize ($filename));
  fclose($handle);

  //Sets up new data
  $final_content = $data.$old_content;

  //Writes new data
  $handle2 = fopen($filename, "w");
  $finalwrite = fwrite($handle2, $final_content);
  fclose($handle2);
}
Lite...

ps: you could also treat the data as an array and then use array_unshift() to add the new data to the beginning
Post Reply