file_put_contents
(PHP 5, PHP 7, PHP 8)
Write data to a file
Description
This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.
If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.
Parameters
filenamePath to the file where to write the data.
dataThe data to write. Can be either a
string, anarrayor astreamresource.If
datais astreamresource, the remaining buffer of that stream will be copied to the specified file. This is similar with usingstream_copy_to_stream().You can also specify the
dataparameter as a single dimension array. This is equivalent tofile_put_contents($filename, implode('', $array)).flagsThe value of
flagscan be any combination of the following flags, joined with the binary OR (|) operator.Flag Description FILE_USE_INCLUDE_PATHSearch for filenamein the include directory. See include_path for more information.FILE_APPENDIf file filenamealready exists, append the data to the file instead of overwriting it.LOCK_EXAcquire an exclusive lock on the file while proceeding to the writing. In other words, a flock()call happens between thefopen()call and thefwrite()call. This is not identical to anfopen()call with mode "x".contextA valid context resource created with
stream_context_create().
Return Values
This function returns the number of bytes that were written to the file, or false on failure.
Falseproblem
Examples
Simple usage example
<?php
$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>Using flags
<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file,
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>