codescracker


php

PHP Write to File



« Previous Tutorial Next Tutorial »


To write some content to a file, first you have to open that file in writing mode. The code to open a file in writing mode is w, you have already learned about it in previous tutorial.

The w opens a file in writing mode and if file doesn't exist inside the current directory, then this mode creates a new file. Let's take an example to understand about writing to a file using PHP.

PHP Write to File Example

Let's see an example shows how to write some cotent to a file in PHP.

Here is an example of writing to a file in PHP.

<html>
<head>
	<title>Write to a File in PHP</title>
</head>
<body>
<?php
	// $file_name contains name of file to use in this example
	$file_name = "codescracker.txt";
	// opens file in writing mode, creates if not exist
	$file_handle = fopen($file_name, "w");
	// checks whether file is opened or not
	if($file_handle == false)
	{
		echo "<p>Error occurred in opening the file...exiting...</p>";
		exit();
	}
	// writing content to the file codescracker.txt
	fwrite($file_handle, "<p>This is writing to a file tutorial in PHP</p>");
	// writing again to the same file
	fwrite($file_handle, "<p>All the content inside this file is written using PHP program</p>");
	echo "<p>All the content is written to the file successfully.</p>";
	// closing file
	fclose($file_handle);
?>
</body>
</html>

Here is the sample output produced by the above write to a file example code in PHP.

php write to file

After running the above program in your browser, following content is written to the file named codescracker.txt

This is writing to a file tutorial in PHP

All the content inside this file is written using PHP program

Here is the screenshot of written content to the file codescracker.txt using above program in PHP.

writing to file php

If you refresh your browser again and again, then content of the file will be overwritten. Overwritten means, previous content will be deleted and new content will be added. You will learn about how to append content instead of overwrite in next tutorial.


« Previous Tutorial Next Tutorial »




Tools
Calculator

Quick Links
Signup - Login - Give Online Test