PHP Save String Content To File
Posted by in PHP August 27, 2011 Leave a comment

There are several reasons why we need to save something to a file stored on web server. With me, I usually save web site performance log, error log, debug log and cached content into a file or just want to check if a particular is writable.

Below is my PHP function that writes the contents of string to a file.

Note: please make sure you set write permission for the folder contains that file and the file is writable.

PHP Write File

<?php
function write_file($content, $file_name)
{
	$fp = fopen($file_name, 'w');
	fwrite($fp, $content);
	fclose($fp);
}
?>

Usage:

<?php
	$content = "A content wil be written.";
	$file_name = "writable_folder/filename.txt";
	write_file($content, $file_name);
?>

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com