PHP file Operation implementation code sharing _php Tutorial

Source: Internet
Author: User
Tags flock fread readfile
Writing or reading data into a file is basically a three-step process:
1. Open a file (if present)
2. Write/Read files
3. Close this file
L Open File
Before opening the file file, we need to know the path to the file and whether the file exists.
Use $_server["Document_root"] to build a global variable to get the relative path of the site. As follows:
$root = $_server["Document_root"];
Use the function file_exists () to detect whether a file exists. As follows:
If (!file_exists ("$root/order.txt")) {echo ' file does not exist ';}
Next, open the file with the fopen () function.
$fp = fopen ("$root/order.txt", ' ab ');
The fopen () function accepts 2 or 3 or 4 parameters.
The first parameter is the file path, the second is the mode of operation (read/write/append, etc.), and the required parameters.
$fp = fopen ("$root/order.txt", ' ab ');
The third is an optional parameter, and if you need PHP to search for a file in Include_path, you can use it without having to provide a directory name or path.
$fp = fopen ("Order.txt", ' ab ', true);
The fourth is also optional, allowing the file name to start with the protocol name (e.g. http://) and open the file in a remote location, as well as some other protocols, such as FTP, and so on.
If fopen () successfully opens a file, it returns a pointer to the file. In the above we have saved to the $FP variable.

Attached file mode diagram


Write a file
Writing files in PHP is easier. Directly with the fwrite () function.
The prototype of Fwrite () is as follows

int fwrite (Resource handle,string string [, int length]);

The third parameter is optional, indicating the maximum length to write to the file.
The length of the string can be obtained by using the built-in strlen () function, 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 File
1. Open a file in read-only mode
The fopen () function is still used, but the read-only mode opens the file using the "RB" file mode. As follows:

$fp = fopen ("$root/order.txt", ' RB ');
2. Know when to finish reading the file
We use the while loop to read the contents of the file, using the feof () function as the terminating condition of the loop condition. As follows:

while (!feof ($fp)) {
The information to be processed
}
3. Read one row of records at a time
The fgets () function can read a line of content from a text file. As follows:
Copy CodeThe 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 the data until a newline character (\ n) or the file terminator EOF is read, or 998B is read from the file, and the maximum length can be read minus 1 B for the specified length.
4. Read the entire file
PHP provides 4 different ways to read the entire file.
a). ReadFile () function
It can be used without first fopen ($path) files and closing files, or using echo directly. As follows:
ReadFile ("$root/order.txt");
It will automatically export the information of the file 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 looks for files in Include_path, as in the fopen function, the return 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 fopen (). The file pointer is then passed as a parameter to Fpassthru () so that the file content pointed to by the file pointer is output. Then close the file again. As follows:
$fp = fopen ("$root/order.txt", ' RB ');
Fpassthru ($FP);
Fclose ($FP);
The return value is also the total number of bytes read from the file.
Note: Must be fopen and fclose
c). File () function
In addition to exporting the file to the browser, he and the ReadFile () function are the same, which sends the results to an array. As follows:
$fileArray = File ("$root/order.txt");
Each line in the file will be used as each element of the array.
Note: direct use, without fopen and fclose
d). file_get_contents () function
Is the same as ReadFile (), but the function returns the contents of the file as a string instead of outputting the contents of the file directly to the browser, that is, the echo output must be used as follows:

Echo file_get_contents ("$root/order.txt");
Note: direct use, without fopen and fclose
5. Read a character
The FGETC () function reads one character at a time from a file, and it has a file pointer function, which is also the only parameter, and it returns the next character. As follows:
Copy CodeThe 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 drawback of the fgetc () function is that it returns the Terminator EOF of the file, and fgets () does not. You also need to Judge feof () after reading the characters.
6. Read any length
The Fread () function is a byte that reads any length from a file, and the function prototype is as follows:

String Fread (resource fp,int length);
When this function is used, it either reads the number of bytes specified by the length parameter, or reads the end of the file.
Copy CodeThe code is as follows:
$fp = fopen ("$root/order.txt", ' RB ');
Echo fread ($FP, 10); Read 10 bytes
Fclose ($FP);

L Close File
Closing the file is simple, calling the Fclose () function directly, and if true, indicates success, and vice versa. As follows:

Fclose ($FP);
L Delete Files
The unlink () function (without a function named delete) is as follows:

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

You can also refer to the following article
The following is an article on basic file read and write operations, I used to read this article after learning the basic operation of the file, sent here to share with you:
Read the file:
PHP Code:
Copy CodeThe 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 file, 8. "R" is a pattern, 9. Or the way we're going to do it, 10. See the introduction later in this article
11.
$file _read = fread ($file _pointer, FileSize ($file _name));
13.//through file refers to 14. Pin Read File contents
15.
Fclose ($file _pointer);
17.//Close File
18.
. print "The contents of the file read: $file _read";
20.//Display file contents
?>.
22.

Write file:
PHP Code:
Copy CodeThe 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. See later
9.
Fwrite ($file _pointer, "What Do You Wanna Write");
11.//Cut the file 12 first. is 0 bytes in size, 13. Then write
14.
Fclose ($file _pointer);
16.//End
17.
Print "Data successfully written to file";
19.
?>.
21st.

Append to file after:
PHP Code:
Copy CodeThe code is as follows:
1. 2.
3. $file _name = "Data.dat";
4.//absolute path: Homedata.dat
5.
6. $file _pointer = fopen ($file _name, "a");
7.//"W" mode
8.
9. Fwrite ($file _pointer, "What Do You Wanna Append");
10.//Not 11. Cut the file by 12. into 0 bytes, 13. Append data to the end of the file
14.
Fclose ($file _pointer);
16.//End
17.
Print "Data successfully appended to file";
19.
?>.
21st.

The above is just a brief introduction, below we will discuss some deeper.
Sometimes a multi-person write scenario (most often on a Web site with a large traffic) produces useless data written to the file, such as:
Info.file file contents are as follows
|1| mukul|15| male| India (N)
|2| linus|31| male| Finland (N)
Now two people registered at the same time, causing file damage
Info.file
|1| mukul|15| male| India
|2| linus|31| male| Finland
|3| rob|27| male| usa|
bill|29| male| USA
In the example above, when PHP writes Rob's information to a file, Bill also starts writing, which is exactly the time to write the ' n ' of the Rob record, causing file corruption.
We certainly don't want this to happen, so let's take a look at the file lock:
PHP Code:
Copy CodeThe 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 use lock_sh,10. You may need to write 1 directly.
11.
if ($lock) {
13.
$file _read = fread ($file _pointer, FileSize ($file _name));
$lock = Flock ($file _pointer, Lock_un);
16.//If the version is less than php4.0.2,17. Replace Lock_un with 3
18.
19.}
20.
Fclose ($file _pointer);
22.
. print "File content is $file _read";
24.
?>.
26.

In the above example, if two files read.php and read2.php are to access the file, they can all be read, but when a program needs to write, it must wait until the read operation is complete and the file is freed.
PHP Code:
Copy CodeThe 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 below php4.0.2,9. Replace LOCK_EX with 2
10.
One. if ($lock) {
12.
Fwrite ($file _pointer, "What U Wanna Write");
Flock ($file _pointer, Lock_un);
15.//If the version is below php4.0.2,16. Replace Lock_un with 3
17.
18.}
19.
Fclose ($file _pointer);
21st.
Print "Data successfully written to file";
23.
?>.
25.

Although the "W" mode is used to overwrite the file, I don't think it applies.
PHP Code:
Copy CodeThe code is as follows:
1. 2.
3. $file _name = "Data.dat";
4.
5. $file _pointer = fopen ($file _name, "a");
6.
7. $lock = Flock ($file _pointer, LOCK_EX);
8.//If the version is below php4.0.2,9. Replace LOCK_EX with 2
10.
One. if ($lock) {
12.
Fseek ($file _pointer, 0, seek_end);
14.//If the version is less than php4.0rc1,15. Using Fseek ($file _pointer, filsize ($file _name));
16.
Fwrite ($file _pointer, "What U Wanna Write");
Flock ($file _pointer, Lock_un);
19.//If the version is below php4.0.2,20. Replace Lock_un with 3
21st.
22.}
23.
Fclose ($file _pointer);
25.
. Print "Data successfully written to file";
27.
?>.
29.

Hmmm., for append data is a little different from other operations, that is fseek! It is always a good practice to confirm that the file pointer is at the end.
If it is under Windows system, the file name above must be preceded by a ".
Flock:
Flock () is locked only when the file is open. The file is locked after it is opened, and now the contents of the file are only in the content at that time and do not reflect the results of other program operations, so it is not only the file append operation, but also the read operation should use Fseek.
(the translation may not be very precise here, but I think it's a good idea.)
About Patterns:
' R '-read-only open, file pointer placed on file header
' r+ '-read and write mode open, the file pointer is placed on the file header
' W '-only write open, the file pointer is placed on the file header, the file is clipped to 0 bytes, if the file does not exist, try to build the file
' w+ '-read and write open, the file pointer is placed on the file header, the file size is clipped to 0 bytes, if the file does not exist, try to build the file
' A '-write-only open, the file pointer is at the end of the file, if the file does not exist, try to create a file
' A + '-read and write open, file pointer at the end of the file, if the file does not exist, try to create a file
By the way, the code that creates the file directory
Copy CodeThe code is as follows:
Create a similar ". /.. /.. Directory of/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); mkdir function Create directory
}
}
}
Calls such as Createdirs ("xxx/xxxx/xxxx",);
Use $globals["Dirseparator" in the original function I changed it to '/'
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 information about the operation of the file code, I believe that beginners are very useful, posted here, I hope there is a point of the function!

http://www.bkjia.com/PHPjc/324316.html www.bkjia.com true http://www.bkjia.com/PHPjc/324316.html techarticle writing or reading data into a file is basically divided into three steps: 1. Open a file (if one exists) 2. Write/Read file 3. Close this file L open the file before opening the file file, ...

  • Related Article

    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.