Jump to content

Recommended Posts

Ok, I've got an interesting question.

 

Is there such thing as a "backwards" append? By backwards, instead of appending to the END of the file, it appends to the BEGINNING?

 

Yes, I know you can do something like

 

$message = sanitize($_POST['message'])."\n".file_get_contents("some_file.txt");
$fp = fopen("some_file.txt","w");
fwrite($fp,$message);
fclose($fp);

 

And the end result would be the same. However, I was wondering if there was a way to do it WITHOUT having to read out the whole file and overwriting that same file? (and why in the world couldn't PHP have a backwards append? They've already got one to add to the end of the file, why not to the beginning?)

Link to comment
https://forums.phpfreaks.com/topic/122176-fwrite-is-there-any-other-way/
Share on other sites

The general way of doing this is:

 

1) read the entire file into an array

2) reverse the array

3) add the line you want to put at the beginning of the file at the end of the array

4) reverse the array

5) write it out

 

<?php
$file_array = map_array('trim',file('yourfile.here'));
$file_array = array_reverse($file_array);
$file_array[] = 'The line goes here';
file_put_contents('yourfile.here',implode("\n",array_reverse($file_array)));
?>

 

Ken

Not all array functions start with array_. You have all the sort functions. It's not only functions, but the parameters functions take. I get so confused sometimes I keep on referring to the manual to ensure I am putting the correct parameter in the correct position. :)

Not all array functions start with array_. You have all the sort functions. It's not only functions, but the parameters functions take. I get so confused sometimes I keep on referring to the manual to ensure I am putting the correct parameter in the correct position. :)

 

I meant all functions that: strpos("some_array_function", "array")  :). Yeah actually it's really confusing remembering the parameters position or optional parameter constants. I suffered this (and a lot more) a bit while taking some simulation tests for the zend zce. It needs quite good memory, but at least it has the greatest documentation ever.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.