iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP File Create / Write

Two main ways to write — high-level file_put_contents() or low-level fopen + fwrite. Pick by whether you have all the data at once.

Single-shot write

PHP
file_put_contents('hello.txt', "first line\nsecond line\n");

Overwrites the file if it exists, creates it otherwise.

Append

PHP
file_put_contents('log.txt', date('c') . " event\n", FILE_APPEND | LOCK_EX);

FILE_APPEND = add to end. LOCK_EX = exclusive lock — prevents two processes from interleaving writes.

Streaming with fwrite

PHP
$fh = fopen('out.txt', 'w');
fwrite($fh, "header\n");
foreach ($rows as $r) {
    fwrite($fh, $r . "\n");
}
fclose($fh);

Mode quick reference

ModeBehaviour
wWrite; truncates existing or creates new.
aAppend.
xCreate-exclusive — fails with warning if file already exists.
r+Read + write; pointer at start; doesn't truncate.

Atomic write

If a write must either fully succeed or not happen at all, write to a temp file then rename() — atomic on POSIX:

PHP
$tmp = tempnam(sys_get_temp_dir(), 'app_');
file_put_contents($tmp, $payload);
rename($tmp, 'data.json');

CSV

PHP
$fh = fopen('out.csv', 'w');
fputcsv($fh, ['name', 'email']);             // header
foreach ($users as $u) {
    fputcsv($fh, [$u->name, $u->email]);
}
fclose($fh);
Tip: Don't forget the LOCK_EX flag (or fopen's flock()) for log files. Concurrent writes without locking shred your logs.

Example

Example
<?php
$fh = fopen('hello.txt', 'w');
fwrite($fh, "line one\n");
fwrite($fh, "line two\n");
fclose($fh);
Try it Yourself »

Exercise

Atomic write — rename the temp file with…

($tmp, 'data.json');

Test yourself

Q1. Atomic write pattern is…
Q2. Append mode is…
Q3. Create-exclusive (fail if exists) is…

Discussion

Loading…