Using PHP file_put_contents() to Write Data to Files
This article explains how to use PHP's file_put_contents() function to write strings or arrays to files, demonstrates flag options for appending and locking, and briefly mentions context resources for advanced file operations.
PHP provides the file_put_contents() function for writing data to files, accepting up to four parameters: the filename, the data, optional flags, and an optional context resource.
Function syntax:
<code>int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )</code>Writing a string to a file
<code>$file = "test.txt";
$data = "Hello, world!";
file_put_contents($file, $data);
</code>Running this code creates test.txt in the current directory with the content "Hello, world!".
Writing an array to a file
<code>$file = "users.txt";
$data = array(
array("name" => "John", "age" => 25),
array("name" => "Emma", "age" => 28),
array("name" => "Michael", "age" => 31)
);
file_put_contents($file, var_export($data, true));
</code>The array is converted to a string with var_export() before being written. After execution, users.txt contains a PHP‑style array representation of the data.
Flag options
FILE_USE_INCLUDE_PATH : Search for the file using the include_path.
FILE_APPEND : Append data to the end of the file instead of overwriting.
LOCK_EX : Acquire an exclusive lock while writing to prevent concurrent writes.
Example of appending data:
<code>$file = "log.txt";
$data = "New log entry";
file_put_contents($file, $data, FILE_APPEND);
</code>This adds "New log entry" to log.txt without erasing existing content.
Context parameter
The fourth parameter allows passing a stream context for more advanced file operations; details can be found in the PHP documentation.
Summary
Using file_put_contents() , developers can easily write strings or arrays to files, control behavior with flags such as FILE_APPEND and LOCK_EX , and optionally provide a context for complex scenarios.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.