String

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.

Syndicate content
Honey Pot that kill bots