PHP makes writing to files straightforward with both convenience functions and low-level handles.
file_put_contents() writes a string to a file, creating it if necessary.
Pass FILE_APPEND flag to append instead of overwrite.
fopen() + fwrite() offer granular control and better performance for repeated writes.
Example
<?php
$path = '/var/data/log.txt';
// Write (overwrites existing content)
file_put_contents($path, "Hello, World!
");
// Append
file_put_contents($path, "Another line
", FILE_APPEND | LOCK_EX);
// Write array of lines
$lines = ['Line 1', 'Line 2', 'Line 3'];
file_put_contents($path, implode("
", $lines) . "
");
// Low-level write with fopen
$handle = fopen($path, 'a'); // 'a' = append, 'w' = overwrite
if ($handle === false) {
throw new RuntimeException("Cannot open $path for writing");
}
try {
fwrite($handle, date('Y-m-d H:i:s') . " — Event logged
");
fwrite($handle, "Additional data
");
} finally {
fclose($handle);
}
// Atomic write — write to temp then rename (prevents partial reads)
$tmpPath = $path . '.tmp.' . uniqid('', true);
file_put_contents($tmpPath, $newContent, LOCK_EX);
rename($tmpPath, $path); // atomic on most systems
Pro Tip
Tip: For log files and other concurrent-write scenarios, always pass the LOCK_EX flag to file_put_contents(). This acquires an exclusive lock, preventing multiple processes from writing simultaneously and corrupting the file.