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
| Mode | Behaviour |
|---|---|
w | Write; truncates existing or creates new. |
a | Append. |
x | Create-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');
Six letters.
Discussion
Loading…