PHP Write File – Complete Guide
PHP provides multiple ways to write to a file. The most common functions are:
fwrite()
file_put_contents()
Writing to a File Using fwrite()
Step 1: Open a File for Writing
$file = fopen("example.txt", "w"); // Open file in write mode
if ($file) {
fwrite($file, "Hello, this is a test file!");
fclose($file);
echo "File written successfully!";
} else {
echo "Error opening file.";
}
✅ "w"
mode creates a new file or overwrites an existing one.
✅ Always close the file with fclose()
after writing.
Append Data to a File Using fwrite()
$file = fopen("example.txt", "a"); // Open file in append mode
if ($file) {
fwrite($file, "\nNew content added.");
fclose($file);
echo "Content appended successfully!";
} else {
echo "Error opening file.";
}
✅ "a"
mode appends data instead of overwriting.
Writing to a File Using file_put_contents()
file_put_contents("example.txt", "This is a new line.");
✅ This function is simpler than fwrite()
.
✅ Overwrites existing content.
To append instead of overwriting:
file_put_contents("example.txt", "\nAppending a new line.", FILE_APPEND);
Handling Errors When Writing a File
$file = "example.txt";
if (is_writable($file)) {
file_put_contents($file, "Writing safely.");
echo "File written successfully!";
} else {
echo "Cannot write to file.";
}
✅ Always check if the file is writable before writing.
Best Practices for Writing Files in PHP
🔹 Use file_put_contents()
for simple writes.
🔹 Use fwrite()
for large files or appending data.
🔹 Ensure the file has the correct permissions.
🔹 Close files after writing (fclose()
).
Complete PHP Write File Code Example
$file = "example.txt";
if ($handle = fopen($file, "w")) {
fwrite($handle, "Hello, PHP File Writing!");
fclose($handle);
echo "File written successfully!";
} else {
echo "Error: Unable to open file.";
}