There are several types of files written in php. One is implemented using the fopen and fwirte functions, and the other is using file_put_contents for read/write. I will introduce their usage below. There are several types of files written in php. One is implemented using the fopen and fwirte functions, and the other is using file_put_contents for read/write. I will introduce their usage below.
Script ec (2); script
Method 1: Using fopen and fwirte Functions
1. How to open a file in PHP
Use the PHP function fopen () to open a file. fopen () usually uses two parameters to indicate the path and file mode for opening the file. For example:
| The Code is as follows: |
|
$ Fp = fopen ("../cnbruce.txt", 'w ');
|
Specifically, "../cnbruce.txt" indicates the path of the cnbruce.txt file (relative to the path of the current execution program file), and 'w' indicates opening the text file in write-only mode.
For file writing
Fwrite (file, string, length)
Parameter description:
File is required. Specifies the open file to be written.
String is required. Specifies the string of the file to be written.
Length is optional. Specifies the maximum number of bytes to write.
Example
| The Code is as follows: |
|
|
/**
* File writing functions
*
* @ Param string $ filename file name
* @ Param string $ text the text string to be written
* @ Param string $ openmod text writing mode ('W': overwrite, 'A': Text append)
* @ Return boolean
*/
Function write_file ($ filename, $ text, $ openmod = 'W '){
If (@ $ fp = fopen ($ filename, $ openmod )){
Flock ($ fp, 2 );
Fwrite ($ fp, $ text );
Fclose ($ fp );
Return true;
} Else {
Return false;
}
} |
Method 2: Use file_put_contents to implement read/write
The file_put_contents function has a very useful parameter LOCK_EX. After it is added, NO content is missing.
This parameter LOCK_EX is straightforward, that is, when writing a file, first lock the file, so that only a client can access the write, other clients can not access the write.
My usage is as follows:
| The Code is as follows: |
|
|
File_put_contents ($ file, $ content, FILE_APPEND | LOCK_EX) |
Explanation:
$ File => This is the path of the written file + file name.
$ Content => This is the content of the written file.
FILE_APPEND => directly Append content to the existing content of the file
LOCK_EX => lock when writing files to prevent content loss caused by simultaneous writing by multiple users