PHP creates or updates files on disk using file_put_contents() for single-shot writes or fopen() combined with fwrite() for streaming writes. Because multiple web requests can write to the same file simultaneously, proper write modes and file locking prevent corrupted data.
Picking 'w' versus 'a' determines whether existing file contents are erased or preserved.
| Mode | File Missing | Existing Content | Pointer |
|---|---|---|---|
'w' |
Creates file | Truncates to zero length | Start |
'a' |
Creates file | Preserves content | End (append) |
'x' |
Creates file | Fails (false) if file exists |
Start |
'c' |
Creates file | Preserves content | Start |
For simple append or overwrite tasks, file_put_contents() with FILE_APPEND and LOCK_EX is shorter and safer than manual fopen() calls.
<?php
declare(strict_types=1);
$logDir = __DIR__ . '/logs';
if (!is_dir($logDir)) {
mkdir($logDir, 0755, true);
}
$logPath = $logDir . '/events.log';
$entry = sprintf("[%s] User #42 updated profile
", date('c'));
// FILE_APPEND preserves existing lines; LOCK_EX blocks concurrent writes
file_put_contents($logPath, $entry, FILE_APPEND | LOCK_EX);
When writing large generated exports, open the file with fopen($path, 'wb'), acquire an exclusive lock using flock($handle, LOCK_EX), write chunks with fwrite(), and release the lock before fclose(). For critical JSON or config files, write to a temporary file first and swap it into place with rename(), which is atomic on POSIX filesystems.
LOCK_EX under concurrent traffic: Two simultaneous PHP workers appending to the same log or JSON file can interleave bytes and corrupt the file.'w': Mode 'w' wipes the entire file immediately on fopen(). Use 'a' for logs or 'x' to create a file only if it does not already exist.mkdir() without recursive: true: Creating nested folders like storage/exports/2026 fails unless the third parameter is true.LOCK_EX do in file_put_contents()?LOCK_EX acquires an exclusive advisory lock on the file while writing, forcing other PHP requests writing to the same file to wait until the write finishes.
Check is_file($path) first, then call unlink($path) to remove the file from disk.
file_put_contents() return false?Common causes include missing parent directories, insufficient folder write permissions for the web server user (www-data), or a full disk.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.