PHP Write to File

A simple function that writes whatever you pass to it in a file.

<?
function write_to_file($fn, $str)
{
	if ($str == '') return 'Nothing to write...';
	if ($fn == '') return 'No file to write to...';
	if (($fp = @fopen($fn, 'w')) === false) return 'Error obtaining file handle';
	if (@fwrite($fp, $str, strlen($str)) === false)
	{
		fclose($fp);
		return 'Error writing to file';
	}
	fclose($fp);
	return 'Data written to file successfully';
}
?>

Usage

Possibly you need to check your permissions in order for PHP to write to the file. This function will overwrite what's in the file if you call it again. Check PHP's site for fopen modes: http://www.php.net/manual/en/function.fopen.php How to: <pre> $str = 'This is a string...'; echo write_to_file('/home/tester/myfile.txt', $str); </pre>


Comments

Add your comment