PHP File Write And Append

PHP File Write & Append – Writing Data to Files ✍️

PHP allows you to write and append data to files easily. Whether you’re saving user input, logging events, or creating reports, you’ll need these functions to store data in files.


🔹 Writing to a File in PHP

The fwrite() function is used to write content to a file. It requires:

  • File Handle: Opened using fopen().
  • Content: The data to write.

File modes for writing:

  • w – Write mode (erases content if file exists, or creates a new file).
  • w+ – Read & write mode (erases existing content).
<?php
$file = fopen("example.txt", "w"); // Open file in write mode
fwrite($file, "Hello, PHP file writing! ✍️"); // Write content
fclose($file); // Close the file
echo "File written successfully!";
?>

Try It Now


🔹 Appending Data to a File

Appending data means adding new content without overwriting existing content.

File modes for appending:

  • a – Append mode (adds content at the end, file must exist).
  • a+ – Read & append mode.
<?php
$file = fopen("example.txt", "a"); // Open file in append mode
fwrite($file, "\nNew line added! 🚀"); // Append new content
fclose($file); // Close the file
echo "Content appended successfully!";
?>

Try It Now


🔹 Writing to a File in One Line

PHP provides file_put_contents() as a shortcut for writing files.

<?php
file_put_contents("example.txt", "Quick write! ⚡");
echo "File written successfully!";
?>

Try It Now

To append using file_put_contents(), use the FILE_APPEND flag:

<?php
file_put_contents("example.txt", "\nAppending with file_put_contents! 🎯", FILE_APPEND);
echo "Content appended successfully!";
?>

Try It Now


🎯 Key Takeaways

  • fwrite() writes data to a file.
  • w mode overwrites existing content, while a mode appends new content.
  • file_put_contents() is a simple way to write or append data.
  • Always close files after writing with fclose().

📝 Practice Time!

Try writing and appending different messages to a file. Experiment with different modes and see what happens! 🚀