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

PHP File Create/Write

Reading files is only half of file handling -- scripts often need to create new files or write data into existing ones too, like saving a log entry, generating a report, or storing uploaded content. fopen() in a write mode, paired with fwrite() or the simpler file_put_contents(), handles exactly this.

Writing a File with file_put_contents()

file_put_contents($filename, $data) writes the given string to a file in one call, creating the file if it does not already exist -- the simplest way to save data to disk without manually opening, writing, and closing a file handle.

Note: Use file_put_contents() as your default for simple one-shot writes, reserving fopen/fwrite for situations needing more control, like writing in chunks.

Warning: file_put_contents() completely overwrites the target file's existing contents by default, unless the FILE_APPEND flag is passed.

Example: Writing a File with file_put_contents()

php
<?php
file_put_contents("data.txt", "Saved in one call");
echo file_get_contents("data.txt");
?>

Opening a File for Writing with fopen()

fopen($filename, "w") opens a file specifically for writing -- if the file already exists, its contents are immediately erased; if it does not exist, PHP creates a new, empty file at that path, ready for fwrite() calls.

Note: Use fopen() with "w" mode (rather than file_put_contents()) when you need to write to the same file multiple times across a script without reopening it each time.

Warning: The moment fopen($path, "w") succeeds, the target file is already truncated to zero bytes -- even if you never actually call fwrite() afterward.

Example: Opening a File for Writing with fopen()

php
<?php
file_put_contents("data.txt", "old content");
$handle = fopen("data.txt", "w");
fwrite($handle, "new content");
fclose($handle);
echo file_get_contents("data.txt");
?>

Appending to a File Without Erasing It

fopen($filename, "a") opens a file in append mode -- new content written with fwrite() is added to the end of the file's existing contents, rather than erasing them, which is exactly what you want for something like a growing log file.

Note: Use append mode ("a") specifically for logs and similarly growing files, where each new write should add on rather than replace what came before.

Warning: Using "w" mode instead of "a" for a log file will silently erase all previous log entries every time the script runs, which is rarely the intended behavior.

Example: Appending to a File Without Erasing It

php
<?php
file_put_contents("log.txt", "First entry\n");
$handle = fopen("log.txt", "a");
fwrite($handle, "Second entry\n");
fclose($handle);
echo file_get_contents("log.txt");
?>

Creating a New File Only If It Doesn't Already Exist

The "x" mode for fopen() creates a new file for writing, but fails (returning false) if a file already exists at that path -- useful when overwriting an existing file would be a mistake, like generating a uniquely-named export file.

Note: Use "x" mode combined with a uniquely generated filename (like one including a timestamp) when accidentally overwriting an existing file must be avoided entirely.

Warning: Unlike "w", which silently overwrites, "x" mode fails loudly (returns false) if the file already exists -- always check its return value.

Example: Creating a New File Only If It Doesn't Already Exist

php
<?php
$handle = fopen("newfile.txt", "x");
echo $handle ? "Created" : "Already exists";
if ($handle) fclose($handle);
$handle2 = @fopen("newfile.txt", "x");
echo $handle2 ? "Created again" : " -- second attempt failed since it now exists";
?>

Checking Write Success and Handling Errors

Both fwrite() and file_put_contents() return false (or the number of bytes written) rather than throwing an exception on failure -- checking that return value is the only reliable way to detect a failed write, such as one caused by a full disk or missing directory permissions.

Note: Wrap file-writing code in checks for the return value, and log or surface an error message when a write unexpectedly fails, rather than assuming it always succeeds.

Warning: A directory without write permission for the web server's user will cause every write attempt inside it to fail silently unless you explicitly check the return value.

Example: Checking Write Success and Handling Errors

php
<?php
$result = file_put_contents("data.txt", "some data");
if ($result === false) {
    echo "Write failed";
} else {
    echo "$result bytes written";
}
?>
Common Mistakes
  1. Opening a file in "w" mode when you meant to add to the end of an existing file -- "w" truncates (erases) the file's existing contents immediately upon opening.
  2. Forgetting to check the return value of fwrite() or file_put_contents(), both of which return false on failure (like a permissions problem) rather than throwing an exception.
  3. Writing to a file without appropriate server permissions set on the target directory, causing every write attempt to silently fail.
Chapter Summary
  • fopen($path, "w") opens a file for writing, creating it if it does not exist and erasing its existing contents if it does.
  • fopen($path, "a") opens a file for appending, adding new content to the end without erasing what was already there.
  • file_put_contents($path, $data) is a one-line shortcut that writes a whole string to a file without needing fopen/fwrite/fclose separately.
Browser Support

File-writing functions have been part of PHP since its earliest versions and behave consistently across every server environment with writable filesystem access.

🔒

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.