Create or write/append in text file

Create or write/append in text file

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

The Tricky Business of Appending to Log Files

You are facing two distinct challenges here: ensuring a file is created if it doesn't exist, and correctly appending new lines without overwriting existing data. Your current approach uses the "w" flag in fopen(), which stands for write. This mode is destructive by nature; it truncates the file to zero length immediately upon opening. If you run your script while logged out, then log back in, that initial "wr" call wipes your entire history before you can add a single line.

To solve this, you must switch the file access mode from "w" to "a", which stands for append. This flag tells PHP to open an existing file for writing and place the write pointer at the end of the file. Crucially, if the file does not exist, the "a" flag will create it automatically without truncating anything.

Here is how you should structure the fopen() call:

$myfile = fopen("logs.txt", "a") or die("Unable to open file!");

By switching to "a", the first line of your code ($txt = "user id date";) needs adjustment. If you are trying to write a header every time a user logs in, you will end up repeating "user id date" on every single login event. A better strategy is to write the header only once when the file is first created. You can detect if this has happened by checking the file's size before opening it. If the file exists and is larger than zero bytes, skip the header line; otherwise, open with "w" mode to create/empty it and write the header, or rely on a dedicated initialization script.

$filepath = "logs.txt";

// Initialize file with header only if it doesn't exist or is empty
if (!file_exists($filepath) || filesize($filepath) == 0) {
    $myfile = fopen($filepath, "w") or die("Unable to create file!");
    $txt = "user id|date|ip_address\n"; // Use \n for cross-platform compatibility
    fwrite($myfile, $txt);
    fclose($myfile);
}

// Always append subsequent logs
$myfile = fopen($filepath, "a") or die("Unable to open file!");
$txt = "12345|2023-10-27 10:00:00|192.168.1.1\n";
fwrite($myfile, $txt);
fclose($myfile);

Handling Concurrency and Race Conditions

Your second concern regarding two users logging in simultaneously is valid. If two processes try to write to the same file at the exact same moment without coordination, you risk data corruption or lost records. This is known as a race condition. While modern operating systems handle file locking somewhat gracefully, relying solely on sequential execution is risky in high-load environments.

In PHP, you can mitigate this using flock(), which provides advisory file locking. You must acquire an exclusive lock before writing and release it afterward. Note that flock() behaves differently depending on whether the file is opened with r+/w/a modes; usually, you need to open the file in a read-write mode even if you intend to append, or use specific flags depending on your PHP version.

$myfile = fopen("logs.txt", "c+") or die("Unable to open file!"); // 'c+' creates file if needed and allows seeking
flock($myfile, LOCK_EX); // Acquire exclusive lock

$txt = "12345|2023-10-27 10:00:00\n";
fwrite($myfile, $txt);

flock($myfile, LOCK_UN); // Release lock
fclose($myfile);

The "c+" mode is interesting here because it creates the file if it does not exist (like 'w') but preserves existing content (unlike 'w' which truncates). However, mixing creation logic with locking requires care. Often, a simpler pattern is to initialize the file separately and then exclusively append to it using "a" mode combined with flock().

Why Text Files Aren't Always Enough

While appending to a local text file is simple to implement, it introduces significant architectural limitations as your application scales. Log files are not transactional databases. They do not support atomic writes out of the box without complex locking strategies, making them prone to partial writes if the server crashes during an operation. Furthermore, reading and parsing large text logs becomes a performance bottleneck compared to querying a structured database or using a dedicated log aggregator like the ELK stack (Elasticsearch, Logstash, Kibana).

If you are building a commercial application where audit trails are critical, consider integrating with Laravel's logging system directly. The framework provides robust channels that can route logs to files, databases, or external services like Sentry, ensuring consistent formatting and easier retrieval without manual file manipulation. You might find relevant implementations and best practices for structured logging at https://laravelcompany.com when looking into how to handle high-volume events efficiently within a Laravel ecosystem.

Ultimately, using fopen() with the "a" flag solves your immediate problem of appending lines, but you must manage headers carefully and consider concurrency if your application sees heavy traffic.

Our network