In PHP, file_put_contents() writes data to a file in a single call. It creates the file if it does not exist and, by default, replaces the old content.
It is the easiest way to save text, logs or JSON. You do not need fopen(), fwrite() and fclose(). Add the FILE_APPEND flag when you want to add to the end of a file instead of overwriting it.
Syntax
Call file_put_contents() with the values you need. Start with this line.
PHP
$bytes = file_put_contents('data.txt', 'Hello');
Call
What it does
file_put_contents('data.txt', 'Hello')
Creates or overwrites data.txt and returns the number of bytes written.
file_put_contents('log.txt', $line, FILE_APPEND)
Adds the text to the end of the file.
file_put_contents('data.txt', $text, LOCK_EX)
Locks the file while writing, so two scripts do not write at once.
The data can be a string, an array or a stream resource. An array is joined together like implode('', $array). The function overwrites existing files unless you add FILE_APPEND.
The first call creates the file and writes Line 1.
The second call uses FILE_APPEND, so Line 2 is added at the end.
Without FILE_APPEND, the second call would erase Line 1.
file_get_contents() shows both lines in the file.
Frequently Asked Questions
It writes data to a file in one step. It creates the file if needed and replaces the old content, unless you use FILE_APPEND.
Pass FILE_APPEND as the third argument. You can add LOCK_EX with the | operator to prevent two scripts from writing at the same time.
Yes. The strings in the array are joined together with nothing between them, like implode('', $array). Add your own line breaks if you need them.
The folder may not exist, PHP may not have permission to write there, or the disk may be full. Check the warning and the folder permissions.
file_put_contents() opens, writes and closes the file in one call. fwrite() writes to a file you opened yourself, which is better when you write many times.