Core PHP

Create, Write, Append & Read a File

Open a file and create it if it does not exist, write to it, append additional content to it, and read from it in PHP.

FileCreateWriteAppendRead.php

<!DOCTYPE html>
<html>
	<head>
		<title>XoaX.net PHP</title>
	</head>
	<body>
		<h1>Psalm 115</h1>
		<pre>
<?php
			// Create a new file. If the file exists, this will remove its content.
			// Write two lines to a file. 
			$qNewFile = fopen("Psalm115.txt", "w") or die("Unable to open file!");
			$sMessage = "4. Their idols are silver and gold, the work of men's hands.\n";
			fwrite($qNewFile, $sMessage);
			$sMessage = "5. They have mouths, but do not speak; eyes, but do not see.\n";
			fwrite($qNewFile, $sMessage);
			fclose($qNewFile);

			// Append another line to the to the file.
			$qNewFile = fopen("Psalm115.txt", "a") or die("Unable to open file!");
			$sMessage = "6. They have ears, but do not hear; noses, but do not smell.\n";
			fwrite($qNewFile, $sMessage);
			fclose($qNewFile);

			// Read the file and output it.
			$qNewFile = fopen("Psalm115.txt", "r") or die("Unable to open file!");
			echo fread($qNewFile, filesize("Psalm115.txt"));
			fclose($qNewFile);
?>
		</pre>
	</body>
</html>
 

Output

 
 

© 2007–2026 XoaX.net LLC. All rights reserved.