Writing and reading PHP files (read only ),
Article outline:
I. Basic Ideas for reading and writing files
Ii. Use the fopen method to open a file
3. File Read and Write operations
4. Use the fclose method to close the file
5. Movement of file pointers
6. Carriage Return and line feed in Windows and UNIX
I. Basic Ideas for reading and writing files:
1. open the file by using the fopen method: $ fp = fopen (/* parameter, parameter */). fp is of the Resource type.
2. Read files or write files (the $ fp returned in 1 is used as the parameter)
3. Call fclose ($ fp) to close the file
Ii. Use the fopen method to open a file
Fopen (file path [string], open mode [string])
<1> the first parameter of fopen is the file path.
Write File Path: 1 absolute path, 2 Relative Path
1 absolute path:
You should be familiar with working in windows. In windows, the path separator is "\" rather than "/", but we cannot use the specified "\" as the separator when writing the path.
What if we write the path with the "\" separator?
<?php $fp = fopen("C:\wamp64\www\text.txt",'w');?>
An error is reported after running, indicating that the path parameter is invalid.
Therefore, we need to replace the separator "\" with "/":
<?php $fp = fopen("C:/wamp64/www/text.txt",'w');?>
If no error is reported during running, the parameter is valid.
Note]The fopen function cannot understand the "\" separator. If you want to use "\", use escape characters, for example, "C: \ wamp64 \ www \ text.txt "can also be written in a way that can be understood by functions without any error. However, "\" is not recommended even in this case, because the OS (mac) can only recognize "/" and cannot recognize "\".
Conclusion: We recommend that you use "/" as the separator.
2. Relative Path:
The previous section describes the absolute path writing method, but this introduces another problem: the directory structure of the server may be greatly changed, at this time, the original absolute path will be overwritten. For example, the target file path on my computer is C:/wamp64/www/text.txt, what if I change the www folder to penghuwan? The original written path parameter is invalid. Therefore, we introduced the relative path statement:
<?php $DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT']; $fp = fopen("$DOCUMENT_ROOT/text.txt",'w');?>
• $ _ SERVER is the Super global variable of PHP (which can be accessed anywhere in the Code and the type is an array ), use $ _ SERVER ['document _ root'] to obtain the default ROOT directory of the SERVER.
The default root directory of the server can be modified through php. ini (this can be Baidu)
• $ _ SERVER ['document _ root'] is equivalent to C:/wamp64/www
Conclusion In this section: relative paths are recommended.
<2> the second parameter of fopen is open mode.
After setting the Enable mode, we set the permission for the next read/write operation:
The basic modes are as follows:
"R": Only files can be read, but files cannot be written (the write operation is ignored)
"W": Only files can be written, but files cannot be read (read operations are ignored)
"A": append only the file, similar to "w". The difference is that "w" deletes the original content. "a" does not delete the original content, but only append the content.
<? Php $ DOCUMENT_ROOT = $ _ SERVER ['document _ root']; $ fp = fopen ("$ DOCUMENT_ROOT/text.txt", 'w'); fwrite ($ fp, 'Write in write mode'); fclose ($ fp);?>
After the write operation permission is set, the file can be normally written to run and C:/wamp64/www/text.txt is opened: this time, we set the permission to read-only, and try to write the text: 'write in read-only mode'
<? Php $ DOCUMENT_ROOT = $ _ SERVER ['document _ root']; $ fp = fopen ("$ DOCUMENT_ROOT/text.txt", 'R'); fwrite ($ fp, 'Write in read mode'); fclose ($ fp);?>
After running the command, Open C:/wamp64/www/text.txt and find that the file content has not changed. This means that the operation has been ignored due to the lack of corresponding permissions, what I think is most likely to find is this table: (the figure is from W3C)
It is comprehensive, but I think this table is not very friendly to new users, so it may not be cloudy. R is read-only, w is write-only (all the original content is deleted), and a is append (the original content is not deleted). This is understandable.
But the difference and connection between r + AND w + AND a + is too vague. Here I want to explain in detail the differences and connections between r +, w +, and a +: r +, w +, and a + are both readable and writable, the reading method is the same. The key lies in the different writing methods:
R +:[Overwrite] the original content from the [header] of the file ([do not delete] the original content );
A +:[Append] content from the [end] of the file ([do not delete] original content );
W +:[Completely delete] the original content, and then [add again] The new content. Next I will demonstrate the above conclusions in turn, first, when the data is not written, the text is "I am initialized value" (meaning I am the initial value)
•
Write text "r + mode" in r + mode"
<?php $DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT']; $fp = fopen("$DOCUMENT_ROOT/text.txt",'r+'); fwrite($fp,'r+ mode'); fclose($fp);?>
Open the text after running, and find that "I am in" is overwritten by "r + mode:
•
Write text "a + mode" in a + mode"Based on the initial text of "I am initialized value", run the following code:
<?php $DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT']; $fp = fopen("$DOCUMENT_ROOT/text.txt",'a+'); fwrite($fp,'a+ mode'); fclose($fp);?>
I am initialized value is not deleted or overwritten, but is added to the new text of a + mode after multiple operations:
• Use w + mode to write the text "w + mode"
Based on the initial text of "I am initialized value", run the following code:
<?php $DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT']; $fp = fopen("$DOCUMENT_ROOT/text.txt",'w+'); fwrite($fp,'w+ mode'); fclose($fp);?>
After running the command, we found that the "I am initialized value" has been deleted and the new text "w + mode" is added. [note] r +, a +, another difference between w + AND a + is that w + creates a file when the file does not exist. If the r + file does not exist, an error is returned. [vomit]: About r + AND w +, the difference between a + is that I have searched the internet, including W3C, various blog articles, and various documents on the "PHP Bible", and found that they are all taken away, this is why I wrote this article.
3. File Read and Write operationsLet's talk about several important functions :•
File_exists (): Determines whether a file exists and returns a Boolean value •
Filesize (): Determines the size of a file. The number of bytes of the returned file is an integer •
Unlink (): Delete an object
Write filesFwrite (Resource file object [string], write mode [string]). The Resource file object is a parameter returned by the fopen method, which is of the Resource type. The Write mode can be w (or w +, a +, r +) is already in the above example. Here we will not release the demo.
Read filesThis is the content of the file to be read:
You can read files in the following ways:
1. Read one byte of data at a time fgetc ()
2. Read the specified number of bytes at a time. fread ()
3. Read one row of Data fgets ()/fgetcsv () at a time ()
4. Read all data at a time
Fpassthru ()/file ()
1. Read one byte at a time-get a single byte through fgetc ()
<? Php $ DOCUMENT_ROOT = $ _ SERVER ['document _ root']; $ fp = fopen ("$ DOCUMENT_ROOT/text.txt", 'R '); // open the file if (file_exists ("$ DOCUMENT_ROOT/text.txt") {// read the content while (! Feof ($ fp) {// determines whether the file pointer reaches the end $ c = fgetc ($ fp); // fgetc (), the file pointer moves one echo $ c backward; // output the obtained bytes} fclose ($ fp); // close the file?>
Run: [note]: whether it is input and output in text format or binary format, fgetc () obtains
BytesInstead of
Character! In the above example, we output data one by one. Now let's make only one output and see how it works:
<? Php $ DOCUMENT_ROOT = $ _ SERVER ['document _ root']; $ fp = fopen ("$ DOCUMENT_ROOT/text.txt", 'R'); echo fgetc ($ fp ); // only one output close ($ fp);?>
The running result is as follows. what we get is not a Chinese character "I", but a garbled text. In fact, this Garbled text is a byte.
<? Php $ DOCUMENT_ROOT = $ _ SERVER ['document _ root']; $ fp = fopen ("$ DOCUMENT_ROOT/text.txt", 'R'); echo fgetc ($ fp ); // outputs echo fgetc ($ fp) three times in a row; echo fgetc ($ fp); fclose ($ fp);?>
2. read multiple bytes at a time-use the fread () method:
<? Php $ DOCUMENT_ROOT = $ _ SERVER ['document _ root']; $ fp = fopen ("$ DOCUMENT_ROOT/text.txt", 'R'); echo fread ($ fp, 3); // output three bytes at a time, that is, a Chinese character (UTF-8) fclose ($ fp);?>
Running result:
Changed:
echo fread($fp, 6);
The running result is as follows, output 6 bytes, that is, two Chinese characters (UTF-8)
3. Read a row at a time -- get the content of a row through fgets ()
<? Php $ DOCUMENT_ROOT = $ _ SERVER ['document _ root'] $ fp = fopen ("$ DOCUMENT_ROOT/text.txt", 'R '); // open the file if (file_exists ("$ DOCUMENT_ROOT/text.txt") {// read the content while (! Feof ($ fp) {// determines whether the object pointer has reached the end $ line = fgets ($ fp); // returns a line of text, and move the file pointer to the next line of header echo $ line. "<br/>"; // output the obtained line of text} fclose ($ fp); // close the file?>
Fgets () actually has a second parameter, which specifies the maximum number of bytes that can be read for each row (note that the number of bytes is not the number of characters ): [note] In the UTF-8 encoding of Chinese Characters 3 bytes, the letter below 1 byte I modify the above line, the Code, so that each row of the maximum number of characters is 3 (that is, 9 bytes)
$line = fgets($fp,10);
Demo: [note]: here, the second parameter in fgets () is 10. Why is it 10? Because 1. The length here is calculated by the number of bytes. 2. A Chinese Character occupies three bytes. Fgets ($ fp, 10) indicates that a maximum of 10-1 = 9 bytes can be read at a time.
4. Read all files at a time-fpassthru () or file ()?
Fpassthru () will read the file and output it directly (no processing process)
<?php $DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT']; $fp = fopen("$DOCUMENT_ROOT/text.txt",'r'); fpassthru($fp); fclose($fp);?>
Running result:
Note]Note that we didn't get the returned value from fpassthru ($ fp) and then echo it to the page. That is to say, this method forces the output of the obtained content, instead of returning text like the method in the previous example, we can save it to a variable to output it.
Saves all the read content to an array. Each array element is a row of content-fille ()
<? Php $ DOCUMENT_ROOT = $ _ SERVER ['document _ root']; $ file_array = file ("$ DOCUMENT_ROOT/text.txt "); // obtain the file array foreach ($ file_array as $ value) {// output the array element echo $ value. "<br/>" ;}?>
[Note]: fopen and fclose are not required here! That is to say, the file () method has already helped us with this step.
4. Use the fclose method to close the fileFclose () returns a Boolean value. If it is successfully closed, it is set to true. If it fails to be closed, it is set to false (the failure rarely occurs. Do you want to disable it after opening the file? 1. Even if you do not hand-write fclose, the file will be automatically closed after the PHP script is executed. 2. If you do not write fclose () to close the file in a script that has been executed for a long time (), file Locking may cause operation blocking. Therefore, writing fclose is a good habit.
5. Movement of file pointersThe functions we call to read files are actually printed Based on the file pointer. Each time a segment of bytes is read, the file pointer moves the length of a segment of bytes backward, until the maximum length of the file to be read
<? Php $ DOCUMENT_ROOT = $ _ SERVER ['document _ root']; function print_file_pointer ($ fp) {// define a function echo that prints the file pointer position "<br/> // The Position of the file pointer at this time:"; echo ftell ($ fp ). "<br/>" ;}$ fp = fopen ("$ DOCUMENT_ROOT/text.txt", 'R'); echo fgetc ($ fp ); // output three bytes of echo fgetc ($ fp); print_file_pointer ($ fp) through fgetc ); // print the position of the file pointer at the moment echo fread ($ fp, 6); // use fread to output 6 bytes print_file_pointer ($ fp) at a time ); // print the position of the file pointer at the moment echo fgets ($ fp); // use fget S outputs a whole line of print_file_pointer ($ fp); // prints the position of the file pointer at the moment fpassthru ($ fp); // outputs all the content print_file_pointer ($ fp) at a time ); // print the position of the file pointer fseek ($ fp, 33) at the moment; // move the file pointer to the 33-byte position print_file_pointer ($ fp ); // print the position of the file pointer at the moment rewind ($ fp); // move the file pointer to the 0-byte position (initial position) print_file_pointer ($ fp ); // print the position of the file pointer at the moment $ fclose ($ fp);?>
Demo: So we need to correctly understand the functions of fgets () and fpassthru:
Fgets ():Instead of outputting a whole line of data
Fpassthru ():From the position of the pointer to the end of all the content of the current file, instead of outputting all the data, you may have questions here: why is the pointer position after "Lake Bay" output 17 instead of 15? It is reasonable to say that the five Chinese characters "My name is Penghu Bay" account for 3*5 = 15 bytes in total. What are the 17-15 = 2 bytes?
The two extra bytes are the carriage return line break \ n \ r in windows.\ N is a line feed, occupies one byte, \ r is a carriage return, occupies one byte, I will introduce in Section 6
6. Carriage Return and line feed in Windows and UNIX
<?php $DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT']; $fp = fopen("$DOCUMENT_ROOT/text.txt",'r'); while(!feof($fp)){ echo fgets($fp); echo ftell($fp); } fclose($fp);?>
When we press enter in windows, it is equivalent to typing \ n \ r, so the 15-byte + 2-byte = 17 of "My name is Penghu Bay" + "\ n \ r" on mac is different: When you press the Enter key, it is equivalent to typing only \ n, so the 15 bytes of "My name is Penghu Bay" + the 1 byte of "\ n" = 16 bytes
The previous article about writing and reading PHP files (which must be read) is all the content shared by the editor. I hope you can give me a reference and support for the help house.