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)
		return 'Error writing to file';
	return 'Data written to file successfully';


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:

How to:
$str = 'This is a string...';
echo write_to_file('/home/tester/myfile.txt', $str);


Add your comment