Prepend string to a file with stream

I hope you have PHP5.
Yesterday someone in Qunu asked me is there a way to prepend a string in front of a file. I said the only way is to load the entire file into the memory, write the string into the file then append the file in the memory into the file.

I told him to check back my site later, I will come up with something better.
So I did, I would post this yesterday but for some real life reasons, it's postponed till today.
I'm a helpful person, you can Qunu me once in a while if you have PHP problem
This function suppose the script can write to the same directory of the script and you are using PHP5.

function prepend($string, $filename){
	$context = stream_context_create ();
	$fp = fopen($filename,'r',1,$context);
	$tmpname = md5($string);
	file_put_contents($tmpname,$string);
	file_put_contents($tmpname,$fp,FILE_APPEND);
	fclose($fp);
	unlink($filename);
	rename($tmpname,$filename);
}

The function first create a stream, a resource. then convert $fp to a stream. The script puts the string into a temporary file, and append the stream to the end. After that, replace the original file with the temporary file.


Thanks!

Ben's picture

This is really great! Works without a hitch.

welcome. I like to rescue

Mgccl's picture

welcome.
I like to rescue people from pain...
like easter bunnies who take eggs from people.

Post new comment

The content of this field is kept private and will not be shown publicly.
If you have a Gravatar account, used to display your avatar.
  • Allowed HTML tags: <img> <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <span> <fn>
  • Lines and paragraphs break automatically.
  • Textual smileys will be replaced with graphical ones.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".
  • Use <fn>...</fn> to insert automatically numbered footnotes.

More information about formatting options

What is 22 + 33?
To combat spam, please solve the math question above.
Honey Pot that kill bots