← Back to PHP Course | Chapter 9: File Handling | Lesson 3 of 8

PHP Writing Files

Writing a file is like writing in a notebook. Be careful, though: opening it one way erases the old pages first, while another way adds new lines at the end.
Syntax
php
$handle = fopen("filename.txt", "w");   // "a" appends instead
fwrite($handle, $data);
fclose($handle);

file_put_contents("filename.txt", $data, FILE_APPEND);

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
<?php
// Declare `$handle`, set to `fopen("data.txt", "w")`
$handle = fopen("data.txt", "w");
// Call `fwrite($handle, "First write")`
fwrite($handle, "First write");
// Call `fclose($handle)`
fclose($handle);
// Print `file_get_contents("data.txt")` to the output
echo file_get_contents("data.txt");
?>

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
<?php
// Declare `$handle`, set to `fopen("data.txt", "a")`
$handle = fopen("data.txt", "a");
// Declare `$bytes`, set to `fwrite($handle, "Appended data")`
$bytes = fwrite($handle, "Appended data");
// Call `fclose($handle)`
fclose($handle);
// Print "$bytes bytes written" to the output
echo "$bytes bytes written";
?>

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
<?php
// Call `file_put_contents("log.txt", "First entry\n")`
file_put_contents("log.txt", "First entry\n");
// Call `file_put_contents("log.txt", "Second entry\n", FILE_APPEND)`
file_put_contents("log.txt", "Second entry\n", FILE_APPEND);
// Print `file_get_contents("log.txt")` to the output
echo file_get_contents("log.txt");
?>

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
<?php
// Declare `$result`, set to `@file_put_contents("/root/protected.txt", "data")`
$result = @file_put_contents("/root/protected.txt", "data");
// Check whether `$result === false`
if ($result === false) {
    // Print "Write failed -- check permissions" to the output
    echo "Write failed -- check permissions";
}
?>

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
<?php
// Declare `$config` as an array: `["theme" => "dark", "lang" => "en"]`
$config = ["theme" => "dark", "lang" => "en"];
// Call `file_put_contents("config.json", json_encode($config))`
file_put_contents("config.json", json_encode($config));
// Print `file_get_contents("config.json")` to the output
echo file_get_contents("config.json");
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using w mode on an existing file and losing its old content; use a to append.
  2. Forgetting to pass FILE_APPEND to file_put_contents, which then overwrites the file.
  3. Writing to a folder without write permission, so the write fails.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.