Scriptplayground

 Print Page | Close Window

Open and Write to File

A simple script used to open a file and write to it.

The path to the file to open.

// File to open
$file = '/path/to/file/example.txt';

Set up the contents that you will be writing to the file.

// Content to write to the file
$contents = "random text to add to the file for example purposes.";

Check to see if the file exists, if it doesn't print an error.

// First check to see if file exists
if(file_exists($file))
	{

Set up a handler for the file and open it.

	// Open for reading and writing
	// Add contents to bottom of the file
	$handle = fopen($file, 'a+');

Write the contents to the file, print an error if we could not write to the file.

	// Attempt to write to the file
	if(!fwrite($handle, $contents))
		{
		print "Error could not write to file '" . $file . "'";
		}

At this point we have done everything that we needed to do to the file so we close it.

	// Finally close the file and wrap up the script
	fclose($handle);

Here is the else that would be called if the file wasn't found.

else
	{
	print "Error file '" . $file . "' doesn't exist.";
	}

Here is the code in full, enjoy.

<?

// File to open
$file = "path/to/file.ext";

// Content to write to the file
$contents = "random text to add to the file for example purposes.";

// First check to see if file exists
if(file_exists($file))
	{
	// Open for reading and writing
	// Add contents to bottom of the file
	$handle = fopen($file, 'a+');

	// Attempt to write to the file
	if(!fwrite($handle, $contents))
		{
		print "Error could not write to file '" . $file . "'";
		}

	// Finally close the file and wrap up the script
	fclose($handle);
	}
else
	{
	print "Error file '" . $file . "' doesn't exist.";
	}

?>

Well that is the end of the article, hope you enjoyed it.


Find this article at:
http://scriptplayground.com/tutorials/php/Open-and-Write-to-File/