PHP Writing Files
In this page:
Writing with fwrite()
fopen($path, w) opens a file for writing, and importantly truncates any existing content first — if you want to add to a file instead of replacing it, use a (append) mode instead.
Example: Writing with fwrite()
<?php
$handle = fopen("data.txt", "w");
fwrite($handle, "First write");
fclose($handle);
echo file_get_contents("data.txt");
?>
Login to try C/C++/Java/PHP code in the editor
Appending with fwrite()
fwrite($handle, $data) writes a string to an open file handle, returning the number of bytes actually written, which is worth checking against the length of your data on systems where disk space might run out.
Example: Appending with fwrite()
<?php
$handle = fopen("data.txt", "a");
$bytes = fwrite($handle, "Appended data");
fclose($handle);
echo "$bytes bytes written";
?>
Login to try C/C++/Java/PHP code in the editor
Simple Writes with file_put_contents()
file_put_contents($path, $data) writes a string to a file in a single call, and accepts a FILE_APPEND flag to add to the end of an existing file instead of overwriting it, similar to fopen()'s a mode.
Example: Simple Writes with file_put_contents()
<?php
file_put_contents("log.txt", "First entry\n");
file_put_contents("log.txt", "Second entry\n", FILE_APPEND);
echo file_get_contents("log.txt");
?>
Login to try C/C++/Java/PHP code in the editor
Appending with file_put_contents()
Writing to a file the web server process doesn't have permission to modify fails silently or with a warning depending on your error settings, which is why checking fwrite()'s return value matters in production code.
Example: Appending with file_put_contents()
<?php
$result = @file_put_contents("/root/protected.txt", "data");
if ($result === false) {
echo "Write failed -- check permissions";
}
?>
Login to try C/C++/Java/PHP code in the editor
Safe File Writing
For structured data like configuration or exported results, it's often better to encode it as JSON with json_encode() before writing, rather than hand-formatting plain text that's harder to read back reliably later.
Example: Safe File Writing
<?php
$config = ["theme" => "dark", "lang" => "en"];
file_put_contents("config.json", json_encode($config));
echo file_get_contents("config.json");
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: