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.
Write to Beginning of File
Moderator: General Moderators
- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
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
A quick funtion to accomplish your task..
Lite...
ps: you could also treat the data as an array and then use array_unshift() to add the new data to the beginning
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);
}ps: you could also treat the data as an array and then use array_unshift() to add the new data to the beginning