File Append Function

Here’s a useful function that I wrote for PHP – it just opens a specified file and appends a string to it. It’s very good for logging things.

<?php
/**
 * @return boolean
 * @param $file FileNameToWriteTo
 * @param $string StringToWriteToFile
 * @desc Writes specified string to the end of the file with a linefeed attached
 */
function file_append($file, $string) {
	if (is_file($file) && is_writable($file)) {
		$fh = fopen($file, 'a');
		if ($fh) {
			fwrite($fh, $string . "\n");
			fclose($fh);
			return true;
		} else {
			return false;
		}
	} else {
		return false;
	}
}
?>

You might want to consider making the fopen() flags ‘ab’ for binary-safe (now reccommended on php.net) and also changing the ‘\n’ part to the appropriate line-endings for your operating system (\n = *NIX, \r\n = Windows, \r = Mac).