In some applications of PHP, you need to write a log or record some information. You can do this using fopen (), fwrite (), and fclose (). You can also simply use file_get_contents () and file_put_contents ().
File_put_contents () write the file. The default is to re-write the file, which will replace the original content. Append the words using the parameter file_append.
Write content in append form when the flags parameter value is File_append, the new data is written in such a way that the content is appended after the contents of the existing file:
file_append: writes data appended to the end of the file
?
12 |
int file_put_contents ( string filename, string data [, int flags [, resource context]] ) file_put_contents ( "log.txt" , "Hello world everyone." , FILE_APPEND); |
Parameter description:
FileName//file name to write data to
Data//To be written. The type can be String,array (but not a multidimensional array), or a stream resource
Flags//optional, which specifies how to open/write files. Possible values:
file_use_include_path://Check the built-in path of the filename copy
file_append://writes data to the end of the file in append form
lock_ex://Lock the file
Context//optional, context is a set of options through which you can modify text properties
There are many times when logging requires a line break. It is not recommended to use \ r \ n because:
In Windows \ r \ n is a newline
In Mac \ r is a newline
In Liunx, \ n is a newline.
But PHP provides a constant to match different operating systems, namely:
Php_eol
?
1 |
file_put_contents ( "log.txt" , "Hello world everyone." .PHP_EOL, FILE_APPEND); |
Implementation of file_put_contents Append and line wrapping in PHP