PHP file_put_contents() Function
The PHP file_put_contents() function writes data to a file.
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.
Syntax
file_put_contents(filename, data, flags, context)
Parameters
filename |
Required. Specify the path to the file where to write the data. If the file does not exist, this function will create one. |
data |
|
flags |
Optional. Specify how to open/write to the file. The possible values are:
|
context |
Optional. Specify a valid context resource created with stream_context_create() function. Context is a set of options that can modify the behavior of a stream. |
Return Value
Returns the number of bytes that were written to the file, or false on failure.
Example: writing data to a file
Lets assume that we have a file called test.txt. This file contains following content:
This is a test file. It contains dummy content.
In the example below, file_put_contents() function is used to write some content to it.
<?php $file = "test.txt"; //displaying the content of the file echo file_get_contents($file)."\n"; //using file_put_contents() function //to write some content to it file_put_contents($file, "Content is modified now."); //displaying the content of the file echo "\n".file_get_contents($file)."\n"; ?>
The output of the above code will be:
This is a test file. It contains dummy content. Content is modified now.
Example: appending data to a file
By using FILE_APPEND flag, we can append content to the file. Consider the example below:
<?php $file = "test.txt"; //displaying the content of the file echo file_get_contents($file)."\n"; //using file_put_contents() function //to write some content to it file_put_contents($file, PHP_EOL."Third line is appended.", FILE_APPEND); //displaying the content of the file echo "\n".file_get_contents($file)."\n"; ?>
The output of the above code will be:
This is a test file. It contains dummy content. This is a test file. It contains dummy content. Third line is appended.
❮ PHP Filesystem Reference