PHP File Create/Write
PHP File Create and Write: Safe Disk Writes and File Locking
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.
Choosing the Right Write Mode
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);
Writing Streams and Ensuring Atomic Config Updates
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.
Common Mistakes to Avoid
- Writing without
LOCK_EXunder concurrent traffic: Two simultaneous PHP workers appending to the same log or JSON file can interleave bytes and corrupt the file. - Overwriting accidentally with
'w': Mode'w'wipes the entire file immediately onfopen(). Use'a'for logs or'x'to create a file only if it does not already exist. - Calling
mkdir()withoutrecursive: true: Creating nested folders likestorage/exports/2026fails unless the third parameter istrue.
Frequently Asked Questions
What does 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.
How do I delete a file safely in PHP?
Check is_file($path) first, then call unlink($path) to remove the file from disk.
Why did 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.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.