0PricingLogin
PHP Academy · Lesson

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 call
  • fopen() + fwrite() — stream-based writing
  • Use FILE_APPEND flag 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

  1. Reading Files with PHP
  2. Writing and Appending to Files
  3. Working with Directories
  4. Handling File Uploads
← Back to PHP Academy