Php file operation implementation code sharing

Source: Internet
Author: User
Tags flock
PHP provides a series of I/O functions to implement the functions we need, including file system operations and directory operations (such as "copy [copy]"). The following describes basic file read/write operations: (1) reading files; (2) writing files; (3) appending to files. There are three steps to write or read data into a file:
1. open a file (if any)
2. write/read files
3. close this file
L open a file
Before opening a file, we need to know the path of the file and whether the file exists.
Use the built-in global variables of $ _ SERVER ["DOCUMENT_ROOT"] to obtain the relative path of the site. As follows:
$ Root = $ _ SERVER ["DOCUMENT_ROOT"];
Use the file_exists () function to check whether a file exists. As follows:
If (! File_exists ("$ root/order.txt") {echo 'file does not exist ';}
Next, use the fopen () function to open the file.
$ Fp = fopen ("$ root/order.txt", 'AB ');
The fopen () function accepts two or three or four parameters.
The first parameter is the file path, and the second parameter is the operation method (read, write, append, and so on). required parameter.
$ Fp = fopen ("$ root/order.txt", 'AB ');
The third is an optional parameter. if you need PHP to search for a file in include_path, you can use it without providing a directory name or path.
$ Fp = fopen ("order.txt", 'AB', true );
The fourth parameter is also an optional parameter. it allows the file name to start with the protocol name (such as http: //) and open the file in a remote location. It also supports some other protocols, for example, ftp.
If fopen () successfully opens a file, a pointer to the file is returned. We saved it to the $ fp variable above.

File mode diagram


Write files
Writing files in PHP is relatively simple. Use the fwrite () function directly.
The fwrite () prototype is as follows:

Int fwrite (resource handle, string [, int length]);

The third parameter is optional, indicating the maximum length of the written file.
You can use the built-in strlen () function to obtain the string length, as follows:

Fwrite ($ fp, $ outputinfo, strlen ($ outputinfo ));

This function tells PHP to save the information in $ outputinfo to the file pointed to by $ fp.
L read files
1. open the file in read-only mode
The fopen () function is still used, but the file is opened in read-only mode, and the file mode is "rb. As follows:

$ Fp = fopen ("$ root/order.txt", 'RB ');
2. know when to read the file
We use the while loop to read the file content and the feof () function as the termination condition of the loop condition. As follows:

While (! Feof ($ fp )){
// Information to be processed
}
3. read a row of records each time.
The fgets () function can read a row of content from a text file. As follows:

The code is as follows:


$ Fp = fopen ("$ root/order.txt", 'RB ');
While (! Feof ($ fp )){
$ Info = fgets ($ fp, 999 );
Echo $ info .'
';
}
Fclose ($ fp );


In this way, he will continue to read data until he reads a line break (\ n), the file terminator EOF, or reads 998B from the file, the maximum length that can be read is the specified length minus 1B.
4. Read the entire file
PHP provides 4 different methods to read the entire file.
A). readfile () function
It can be used directly without fopen ($ path) files or close files or echo. As follows:
Readfile ("$ root/order.txt ");
It automatically outputs the file information to the browser. Its prototype is as follows:
Int readfile (string filename, [int use_include_path [, resource context]);
The second optional parameter specifies whether PHP searches for files in include_path. this is the same as that of the fopen function. the returned value is the total number of bytes read from the file.
Note: Use directly without fopen or fclose
B). fpassthru () function
To use this function, you must first open a file using fopen. Then, the file pointer is passed as a parameter to fpassthru (), so that the file content pointed to by the file pointer can be output. Then close the file. As follows:
$ Fp = fopen ("$ root/order.txt", 'RB ');
Fpassthru ($ fp );
Fclose ($ fp );
The returned value is also the total number of bytes read from the file.
Note: Both fopen and fclose are required.
C). file () function
In addition to outputting a file to a browser, the readfile () function is the same and sends the result to an array. As follows:
$ FileArray = file ("$ root/order.txt ");
Each row in the file is used as each element of the array.
Note: Use directly without fopen or fclose
D). file_get_contents () function
The same as readfile (), but this function will return the file content in the form of a string, instead of directly outputting the file content to the browser, that is, the echo output must be used, as shown below:

Echo file_get_contents ("$ root/order.txt ");
Note: Use directly without fopen or fclose
5. read one character
The fgetc () function reads a character from a file at a time. it has a file pointer function, which is a unique parameter and returns the next character. As follows:

The code is as follows:


$ Fp = fopen ("$ root/order.txt", 'RB ');
While (! Feof ($ fp )){
$ Char = fgetc ($ fp );
If (! Feof ($ fp )){
Echo ($ char = "\ n "? '
': $ Char );
}
}
Fclose ($ fp );


Note: One disadvantage of the fgetc () function is that it returns the object Terminator EOF, while fgets () does not. After reading characters, you also need to judge feof ().
6. read arbitrary length
The fread () function reads any length of bytes from a file. the Function prototype is as follows:

String fread (resource fp, int length );
When this function is used, it either fully reads the number of bytes specified by the length parameter, or reads the end of the file.

The code is as follows:


$ Fp = fopen ("$ root/order.txt", 'RB ');
Echo fread ($ fp, 10); // read 10 bytes
Fclose ($ fp );


L close the file
It is easy to close the file. you can call the fclose () function directly. if true is returned, the operation is successful. Otherwise, the operation is successful. As follows:

Fclose ($ fp );
L delete an object
Unlink () function (no function named delete), as follows:

Unlink ("$ root/order.txt ");
L determine the file size
You can use the filesize () function to view the size of a file (in bytes), as follows:
Echo filesize ("$ root/order.txt ");

You can also refer to the following articles.
The following is an article about basic file read/write operations. I have read this article and learned about basic file operations. I will share it with you here:
Read files:
PHP code:

The code is as follows:


1. 2.
3. $ file_name = "data. dat ";
4. // The absolute path of the file to be read: homedata. dat
5.
6. $ file_pointer = fopen ($ file_name, "r ");
7. // open the file. 8. "r" is a mode, 9. or the operation method we want to perform. 10. for details, refer to the introduction below.
11.
12. $ file_read = fread ($ file_pointer, filesize ($ file_name ));
13. // read the file content by referring to 14.
15.
16. fclose ($ file_pointer );
17. // close the file
18.
19. print "the file content read is: $ file_read ";
20. // display the file content
21.?>
22.


Write file:
PHP code:

The code is as follows:


1. 2.
3. $ file_name = "data. dat ";
4. // absolute path: homedata. dat
5.
6. $ file_pointer = fopen ($ file_name, "w ");
7. // "w" is a mode. 8. for details, refer to the following section.
9.
10. fwrite ($ file_pointer, "what you wanna write ");
11. // cut the File 12 first. it is 0 bytes, 13. then write
14.
15. fclose ($ file_pointer );
16. // end
17.
18. print "data is successfully written to the file ";
19.
20.?>
21.


Append to the end of the file:
PHP code:

The code is as follows:


1. 2.
3. $ file_name = "data. dat ";
4. // absolute path: homedata. dat
5.
6. $ file_pointer = fopen ($ file_name, "");
7. // "w" mode
8.
9. fwrite ($ file_pointer, "what you wanna append ");
10. // not 11. cut the File 12. into 0 bytes, 13. append the data to the end of the file
14.
15. fclose ($ file_pointer );
16. // end
17.
18. print "data is successfully appended to the file ";
19.
20.?>
21.


The above is just a brief introduction. next we will discuss some deeper ones.
Sometimes many people write data (most often on websites with large traffic), and useless data is generated to write files. for example:
The content of the info. file is as follows->
| 1 | Mukul | 15 | Male | India (n)
| 2 | Linus | 31 | Male | Finland (n)
Now two people register at the same time, causing file destruction->
Info. file->
| 1 | Mukul | 15 | Male | India
| 2 | Linus | 31 | Male | Finland
| 3 | Rob | 27 | Male | USA |
Bill | 29 | Male | USA
In the above example, when PHP writes Rob's information to the file, Bill also begins writing. at this time, it is necessary to write 'n' of Rob's record, causing file damage.
We certainly don't want this to happen, so let's look at the file lock:
PHP code:

The code is as follows:


1. 2.
3. $ file_name = "data. dat ";
4.
5. $ file_pointer = fopen ($ file_name, "r ");
6.
7. $ lock = flock ($ file_pointer, LOCK_SH );
8. // I use 4.0.2, 9. so I use LOCK_SH, 10. you may need to write 1 directly.
11.
12. if ($ lock ){
13.
14. $ file_read = fread ($ file_pointer, filesize ($ file_name ));
15. $ lock = flock ($ file_pointer, LOCK_UN );
16. // if the version is earlier than PHP4.0.2, 17. use 3 to replace LOCK_UN
18.
19 .}
20.
21. fclose ($ file_pointer );
22.
23. print "file content: $ file_read ";
24.
25.?>
26.


In the preceding example, if two files are read. php and read2.php both need to access the file, so they can be read, but when a program needs to write, it must wait until the read operation is complete and the file is released.
PHP code:

The code is as follows:


1. 2.
3. $ file_name = "data. dat ";
4.
5. $ file_pointer = fopen ($ file_name, "w ");
6.
7. $ lock = flock ($ file_pointer, LOCK_EX );
8. // if the version is earlier than PHP4.0.2, 9. replace LOCK_EX with 2.
10.
11. if ($ lock ){
12.
13. fwrite ($ file_pointer, "what u wanna write ");
14. flock ($ file_pointer, LOCK_UN );
15. // if the version is earlier than PHP4.0.2, 16. use 3 to replace LOCK_UN
17.
18 .}
19.
20. fclose ($ file_pointer );
21.
22. print "data is successfully written to the file ";
23.
24.?>
25.


Although the "w" mode is used to overwrite files, I don't think it is applicable.
PHP code:

The code is as follows:


1. 2.
3. $ file_name = "data. dat ";
4.
5. $ file_pointer = fopen ($ file_name, "");
6.
7. $ lock = flock ($ file_pointer, LOCK_EX );
8. // if the version is earlier than PHP4.0.2, 9. replace LOCK_EX with 2.
10.
11. if ($ lock ){
12.
13. fseek ($ file_pointer, 0, SEEK_END );
14. // if the version is earlier than PHP4.0RC1, 15. use fseek ($ file_pointer, filsize ($ file_name ));
16.
17. fwrite ($ file_pointer, "what u wanna write ");
18. flock ($ file_pointer, LOCK_UN );
19. // if the version is earlier than PHP4.0.2, 20. use 3 to replace LOCK_UN
21.
22 .}
23.
24. fclose ($ file_pointer );
25.
26. print "data is successfully written to the file ";
27.
28.?>
29.


Hmmm... the append data is a bit different from other operations, that is, FSEEK! It is always a good habit to make sure that the file pointer is at the end of the file.
In Windows, ''must be added before the file name ''.
FLOCK Miscellaneous:
Flock () is locked only after the file is opened. In the above column, the file is locked only after it is opened. the content of the file is only in the current time, but does not reflect the results of other Program Operations. Therefore, it is not just an append operation on the file, fseek should also be used for read operations.
(The translation here may not be very accurate, but I have figured it out ).
Mode:
'R'-Open in read-only mode, and place the file pointer in the file header
'R + '-Open in read/write mode, and place the file pointer in the file header
'W'-Write-only open, the file pointer is placed in the file header, the file is cut to 0 bytes, if the file does not exist, try to create a file
'W + '-open read/write. the file pointer is placed in the file header. the file size is cut to 0 Bytes. if the file does not exist, try to create a file.
'A'-Open in write-only mode. the file pointer is placed at the end of the file. if the file does not exist, try to create a file.
'A + '-open read/write. the file pointer is placed at the end of the file. if the file does not exist, try to create the file.
By the way, the code for creating a file directory

The code is as follows:


// Create a directory similar to "../xxx/xxx.txt"
Function createdirs ($ path, $ mode = 0777) // mode 077
{
$ Dirs = explode ('/', $ path );
$ Pos = strrpos ($ path ,".");
If ($ pos = false) {// note: three equal signs
// Not found, means path ends in a dir not file
$ Subamount = 0;
}
Else {
$ Subamount = 1;
}
For ($ c = 0; $ c <count ($ dirs)-$ subamount; $ c ++ ){
$ Thispath = "";
For ($ cc = 0; $ cc <= $ c; $ cc ++ ){
$ Thispath. = $ dirs [$ cc]. '/';
}
If (! File_exists ($ thispath )){
// Print "$ thispath ";
Mkdir ($ thispath, $ mode); // create a directory using the mkdir function
}
}
}
// Call such as createdirs ("xxx/xxxx ",);
// In the original function, I changed $ GLOBALS ["dirseparator"] '/'
Function recur_mkdirs ($ path, $ mode = 0777) // mode 0777
{
// $ GLOBALS ["dirseparator"]
$ Dirs = explode ($ GLOBALS ["dirseparator"], $ path );
$ Pos = strrpos ($ path ,".");
If ($ pos = false) {// note: three equal signs
// Not found, means path ends in a dir not file
$ Subamount = 0;
}
Else {
$ Subamount = 1;
}


These are just some basic code for file operations. I believe they are useful to beginners. I hope you can introduce them here!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.