PHP file_put_contents Function: Usage, Parameters, and Examples
This article explains PHP's file_put_contents function, detailing its purpose of writing strings, arrays, or streams to files, describing each parameter (filename, data, flags, context), return values, and providing two practical code examples demonstrating basic usage and appending with FILE_APPEND and LOCK_EX flags.
The file_put_contents() function in PHP writes a string, array, or stream to a file, providing a convenient alternative to using fopen() , fwrite() , and fclose() sequentially.
Parameters :
filename : the path of the file to write to.
data : the data to write; can be a string, an array (which will be joined), or a stream resource.
flags : optional integer flags combined with the bitwise OR operator (e.g., FILE_APPEND , LOCK_EX ).
context : a stream context resource.
Return value : the number of bytes written on success, or FALSE on failure.
Example 1 – Basic write :
<?php
$file = 'people.txt';
$current = file_get_contents($file);
$current .= "John Smith\n";
file_put_contents($file, $current);
?>Example 2 – Append with flags :
<?php
$file = 'people.txt';
$person = "John Smith\n";
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
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.