PHP write to file

One of those simple functions that I'm always using. It writes the given string to the end a file. If the file doesn't exist, then it creates it.

$err = write_to_end_of_file("some text", "A_file_name.txt");
if($err) print $err; // If there's been an error let us know
 
function write_to_end_of_file($str, $filename){
	if(!file_exists ($filename )){
		$fp = fopen($filename,"w"); 
		fwrite($fp, '');
		fclose($fp);
	}
	// Read & save old contents
	$old = file_get_contents($filename);
	// Open the file & write to it
	$fp = fopen($filename,"w"); 
	if(!$fp) return "Can't save string to file";
	else fwrite($fp, $old.$str); 
	fclose($fp);
	chmod($filename, 0777); 
	// Alls fine so don't return an error
	return NULL;
}

Comments

Post new comment

  • 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]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <h3> <h2> <h4> <img> <div> <table> <tr> <td> <pre>
  • Lines and paragraphs break automatically.
  • Insert image: [img:node_id align=(left|right) size=(|fullLA|fullPreview|fullSQ|halfLA|halfPO|halfSQ|thirdSQ) action=(popup|link|frame) url=url style="margin:10px;" title=text description=text]

More information about formatting options

 
info@theanthillsocial.co.uk XHTML 1.0 Strict CSS2 WAI