codescracker


php

PHP Append to File



« Previous Tutorial Next Tutorial »


Here you will learn about how to append some content in a file using PHP with example.

If you don't want to delete previous content present inside the file when adding new content, then use append mode to open and append content to the file. To open a file in appending mode in PHP, use a.

PHP Append to File Example

Let's take an example of appending content to a file in PHP.

Here is an example of appending content to file in PHP.

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

Here is the sample output of the above appending to a file example code in PHP.

php append to file

After running the above appending to file code in PHP, the following content is appended to the file named myappendfile.txt

<p>This is appending to a file tutorial in PHP</p><p>All the content inside this file is appended using PHP program</p>

And here is the screenshot of the content of file myappendfile.txt in which the above content is appended using the appending to file PHP program.

appending to file php

Now refresh your browser two times, you will see the content is appended two times in the file. Now the same content presented three times inside the file myappendfile.txt. Here is the screenshot of the content of file named myappendfile.txt after running the above file appending code three times.

php appending to file example

« Previous Tutorial Next Tutorial »








Tools
Calculator

Quick Links
Signup - Login - Give Online Test