Writing and Appending to Files
Write data to files with file_put_contents and FILE_APPEND.
Writing Files in PHP
PHP provides several ways to write to files:
file_put_contents()— write string to file in one callfopen()+fwrite()— stream-based writing- Use
FILE_APPENDflag to append instead of overwrite
file_put_contents()
Write a string to a file — creates the file if it doesn't exist, overwrites if it does:
<?php
$data = "Hello, PHP!\nThis is line 2.\n";
$bytes = file_put_contents('/tmp/output.txt', $data);
if ($bytes === false) {
echo 'Failed to write';
} else {
echo "Wrote $bytes bytes";
}All lessons in this course
- Reading Files with PHP
- Writing and Appending to Files
- Working with Directories
- Handling File Uploads