The file_put_contents () function is used to write a php string to a file. the number of bytes written to the file is returned. if the string fails, FALSE is returned.
Instructions for use:
file_put_contents(file,data,mode,context)
Parameter description:
File name of the data to be written
The data to be written. The type can be string, array (but not multi-dimensional array), or stream resource.
Mode (optional) specifies how to open/write files. Possible values:
1. FILE_USE_INCLUDE_PATH: check the built-in path of the filename copy.
2. FILE_APPEND: Writes data at the end of the file in append mode.
3. LOCK_EX: Lock the file
Parameter description
File |
Required. Specifies the file to write data. If the file does not exist, create a new file. |
Data |
Optional. Specifies the data to be written into the file. It can be a string, array, or data stream. |
Mode |
Optional. Specifies how to open/write files. Possible values: FILE_USE_INCLUDE_PATH FILE_APPEND LOCK_EX |
Context |
Optional. Specifies the file handle environment. Context is a set of options that can modify the behavior of a stream. If null is used, this parameter is ignored. |
Optional. context is a set of options. you can use it to modify text attributes.
Example:
Echo file_put_contents ("test.txt", "This is test.txt ");
?>
Run this example. the browser outputs the length of the character.
The content of the test.txt file (in the same directory as the program) is: This is test.txt
Prompt
? If the file does not exist, the file is created, which is equivalent to the fopen () function.
? If the file exists, content in the file will be cleared by default. you can set the flags parameter value to FILE_APPEND to avoid this (see below ).
? This function can be safely used for binary objects.
Write file content in append mode
When the flags parameter value is set to FILE_APPEND, it indicates that new data is written by appending content after the existing file content:
File_put_contents ("test.txt", "my add contents", FILE_APPEND );
?>
After the program is executed, the content of the test.txt file becomes: This is test.txt my add contents
Note:File_put_contents () actually calls the fopen (), fwrite (), and fclose () functions in turn.