0Pricing
PHP Academy · Lesson

Writing and Appending to Files

Write data to files with file_put_contents and FILE_APPEND.

Writing and Appending to Files is a free PHP Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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";
}

Appending with FILE_APPEND

Add content to the end of an existing file with the FILE_APPEND flag:

<?php
$logEntry = date('Y-m-d H:i:s') . ' - User logged in' . PHP_EOL;

file_put_contents(
    '/var/log/app.log',
    $logEntry,
    FILE_APPEND | LOCK_EX  // append + exclusive lock
);

fopen Write Modes

Open modes for fopen determine how the file is opened:

  • 'w' — write, truncate to zero length or create
  • 'a' — write, append, create if not exists
  • 'x' — write, fail if file already exists
  • 'r+' — read+write from start, file must exist

fopen + fwrite

Stream-based writing for precise control:

<?php
$handle = fopen('/tmp/report.txt', 'w');

if ($handle === false) die('Cannot open file');

fwrite($handle, "Report generated: " . date('Y-m-d') . "\n");
fwrite($handle, str_repeat('-', 40) . "\n");
fwrite($handle, "Total: 1234\n");

fclose($handle);
echo 'Report written';

Writing CSV Files

Use fputcsv() to write correctly-formatted CSV lines:

<?php
$rows = [
    ['Name', 'Email', 'Score'],
    ['Alice', 'alice@test.com', 95],
    ['Bob',   'bob@test.com',   87],
];

$handle = fopen('/tmp/results.csv', 'w');
foreach ($rows as $row) {
    fputcsv($handle, $row);
}
fclose($handle);

Writing JSON Files

Serialize PHP data to JSON and write to a file:

<?php
$config = [
    'version' => '2.0',
    'debug'   => false,
    'db'      => ['host' => 'localhost', 'port' => 3306],
];

$json = json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
file_put_contents('/app/config.json', $json);

echo 'Config saved';

Atomic File Writes

Write to a temp file then rename for atomic (crash-safe) updates:

<?php
$target  = '/app/data.json';
$tmpFile = $target . '.tmp.' . uniqid();

$data = json_encode(['ts' => time(), 'value' => 42]);

file_put_contents($tmpFile, $data, LOCK_EX);
rename($tmpFile, $target);  // atomic on most OSes

echo 'File updated atomically';

Permissions and Ownership

Set file permissions after creation with chmod():

<?php
$path = '/var/www/uploads/avatar.jpg';

// Copy uploaded temp file to destination
move_uploaded_file($_FILES['avatar']['tmp_name'], $path);

// Set permissions (owner read/write, group read, world read)
chmod($path, 0644);

echo 'File uploaded and permissions set';

Temporary Files

Create temp files safely with tempnam() or tmpfile():

<?php
// Create a named temp file
$tmpPath = tempnam(sys_get_temp_dir(), 'php_');
file_put_contents($tmpPath, 'temp data');
$content = file_get_contents($tmpPath);
unlink($tmpPath);  // delete when done

// Anonymous temp file handle
$tmp = tmpfile();
fwrite($tmp, 'anonymous temp');
// auto-deleted when $tmp is garbage collected

File Copy and Move

Copy and rename/move files with built-in functions:

<?php
// Copy a file
copy('/src/template.html', '/dst/page.html');

// Move / rename
rename('/tmp/upload_abc', '/storage/images/photo.jpg');

// Delete
unlink('/tmp/old_file.txt');

// Check if file was copied successfully
if (copy('a.txt', 'backup.txt')) {
    echo 'Backup created';
}

Quick Check

Which flag do you pass to file_put_contents() to add content to the end of a file instead of overwriting it?

Recap: Writing Files

File writing essentials:

  • file_put_contents() — simplest write/overwrite
  • FILE_APPEND flag to append
  • fopen('a', ...) + fwrite() for streaming
  • fputcsv() for CSV output
  • Atomic writes: write to temp + rename()
  • chmod() to set permissions after creation

Frequently asked questions

Is the “Writing and Appending to Files” lesson free?

Yes — the full text of “Writing and Appending to Files” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Writing and Appending to Files”?

Write data to files with file_put_contents and FILE_APPEND. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Writing and Appending to Files” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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