Advertisement
Beginner PHP, File Handling & File System Functions

How do you write data to a file in PHP, and what is the difference between overwriting a file and appending to it?

Short answer

file_put_contents writes data to a file, completely overwriting any existing content by default, while passing the FILE_APPEND flag instead adds the new content to the end of the existing file without removing what was already there, and the fopen function similarly supports…

Save PHP mock interview
Advertisement
AModel answer
file_put_contents writes data to a file, completely overwriting any existing content by default, while passing the FILE_APPEND flag instead adds the new content to the end of the existing file without removing what was already there, and the fopen function similarly supports different modes, such as w for overwriting and a for appending, giving you explicit control over exactly how your write operation should behave.
file_put_contents('log.txt', 'New entry' . PHP_EOL, FILE_APPEND);
Real-world example
A logging system appends each new log entry to the end of an existing log file using the FILE_APPEND flag, ensuring previous log history is always preserved rather than being overwritten every time a new entry is recorded.
Likely follow-ups
  • What happens if you try to write to a file that does not yet exist?
  • How do file permissions affect whether PHP can successfully write to a specific file?
Related topics