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
- Memory Usage:
file_put_contents()loads the entire string into memory before writing it to disk. For small to medium-sized strings (up to a few megabytes), this is extremely fast. However, if you are working with gigabyte-sized strings, usefopen()and awhileloop withfwrite()to stream the data in chunks and prevent PHP memory exhaustion. - Context Options: You can pass a stream context as the fourth parameter if you need to write to remote files (like FTP or HTTP targets) that require specific headers or permissions.