fwrite() & file_put_contents()PHP provides functions to create new files, overwrite existing file content, or append new data to the end of existing files.
file_put_contents($file, $data, $flags): High-level atomic file write shorthand.FILE_APPEND Flag: Appends data to end of existing file.LOCK_EX Flag: Aquires an exclusive file lock during write operation.fopen() with fwrite(): Low-level stream writing method for iterative output.flowchart TD
A["File Writing Task"] --> B{"Choose Strategy"}
B -- Simple Single Operation --> C["file_put_contents($path, $text, FILE_APPEND | LOCK_EX)"]
B -- Iterative Bulk Stream --> D["$h = fopen($path, 'a'); fwrite($h, $text); fclose($h);"]
<?php
declare(strict_types=1);
$auditLogPath = __DIR__ . '/audit.log';
// 1. High-level Atomic Append with Exclusive File Lock
$logEntry = date('Y-m-d H:i:s') . " | EVENT: USER_LOGIN | IP: 192.168.1.50
";
file_put_contents($auditLogPath, $logEntry, FILE_APPEND | LOCK_EX);
// 2. Stream Writing via fopen ('a' mode for append)
$handle = fopen($auditLogPath, 'a');
if ($handle !== false) {
fwrite($handle, date('Y-m-d H:i:s') . " | EVENT: PAYMENT_SUCCESS | Amount: $99.00
");
fclose($handle);
}
echo "Successfully wrote audit records to: " . basename($auditLogPath) . "
";
LOCK_EX When Appending Logs: Prevents corrupted log entries when concurrent processes write to the log file simultaneously.'w' to Overwrite & 'a' to Append: Choose mode carefully; 'w' truncates files to 0 bytes instantly.www-data).Write a line of code using file_put_contents() with the FILE_APPEND flag to append "New Entry " to events.txt!
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.