Efficiently Write String to File with file_put_contents in PHP

This article explains how to use the PHP file_put_contents() function to write a string to a file in the most efficient and secure manner. You will learn the basic syntax, how to append data without overwriting, and how to use flags like exclusive locking to prevent data corruption in high-traffic environments.

The file_put_contents() function is the most efficient way to write a string to a file in PHP because it internally combines fopen(), fwrite(), and fclose() into a single, highly optimized system call.

Basic Usage (Overwriting)

By default, calling file_put_contents() will overwrite any existing content in the destination file. If the file does not exist, PHP will attempt to create it.

$file = 'example.txt';
$data = 'This is the string to write.';

// Writes the string, overwriting any existing content
file_put_contents($file, $data);

Appending Data Efficiently

If you want to add a string to the end of an existing file instead of erasing its current contents, use the FILE_APPEND flag. This is highly efficient because PHP jumps directly to the end of the file to write the new data.

$file = 'log.txt';
$data = "New log entry\n";

// Appends the string to the end of the file
file_put_contents($file, $data, FILE_APPEND);

Preventing Race Conditions with Locking

In concurrent environments—such as busy web servers where multiple users might trigger the file-writing script simultaneously—files can become corrupted if two processes write to them at the same time.

To prevent this, combine your write operation with the LOCK_EX flag. This acquires an exclusive lock on the file while writing, ensuring no other process can write to it at the same millisecond.

$file = 'data.txt';
$data = "Secure and concurrent-safe data.\n";

// Safely appends data using an exclusive lock
file_put_contents($file, $data, FILE_APPEND | LOCK_EX);

Performance Considerations