PHP File Create/Write
In this page:
file_put_contents("filename.txt", $data); // create or overwrite
$handle = fopen("filename.txt", "a"); // "w" overwrites, "a" appends
fwrite($handle, $data);
fclose($handle);
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.
Example: Writing a File with file_put_contents()
<?php
// Call `file_put_contents("data.txt", "Saved in one call")`
file_put_contents("data.txt", "Saved in one call");
// Print `file_get_contents("data.txt")` to the output
echo file_get_contents("data.txt");
?>
Login to try C/C++/Java/PHP code in the editor
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.
Example: Opening a File for Writing with fopen()
<?php
// Call `file_put_contents("data.txt", "old content")`
file_put_contents("data.txt", "old content");
// Declare `$handle`, set to `fopen("data.txt", "w")`
$handle = fopen("data.txt", "w");
// Call `fwrite($handle, "new content")`
fwrite($handle, "new content");
// Call `fclose($handle)`
fclose($handle);
// Print `file_get_contents("data.txt")` to the output
echo file_get_contents("data.txt");
?>
Login to try C/C++/Java/PHP code in the editor
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.
Example: Appending to a File Without Erasing It
<?php
// Call `file_put_contents("log.txt", "First entry\n")`
file_put_contents("log.txt", "First entry\n");
// Declare `$handle`, set to `fopen("log.txt", "a")`
$handle = fopen("log.txt", "a");
// Call `fwrite($handle, "Second entry\n")`
fwrite($handle, "Second entry\n");
// Call `fclose($handle)`
fclose($handle);
// Print `file_get_contents("log.txt")` to the output
echo file_get_contents("log.txt");
?>
Login to try C/C++/Java/PHP code in the editor
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.
Example: Creating a New File Only If It Doesn't Already Exist
<?php
// Declare `$handle`, set to `fopen("newfile.txt", "x")`
$handle = fopen("newfile.txt", "x");
// Print `$handle ? "Created" : "Already exists"` to the output
echo $handle ? "Created" : "Already exists";
if ($handle) fclose($handle);
// Declare `$handle2`, set to `@fopen("newfile.txt", "x")`
$handle2 = @fopen("newfile.txt", "x");
// Print `$handle2 ? "Created again" : " -- second attempt failed since it now exists"` to the output
echo $handle2 ? "Created again" : " -- second attempt failed since it now exists";
?>
Login to try C/C++/Java/PHP code in the editor
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.
Example: Checking Write Success and Handling Errors
<?php
// Declare `$result`, set to `file_put_contents("data.txt", "some data")`
$result = file_put_contents("data.txt", "some data");
// Check whether `$result === false`
if ($result === false) {
// Print "Write failed" to the output
echo "Write failed";
// Otherwise, run this branch
} else {
// Print "$result bytes written" to the output
echo "$result bytes written";
}
?>
Login to try C/C++/Java/PHP code in the editor
- 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.
- 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.
- Writing to a file without appropriate server permissions set on the target directory, causing every write attempt to silently fail.
- 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.
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: