PHP file operation to achieve code sharing _php skills

Source: Internet
Author: User
Tags create directory explode flock fread function prototype mkdir readfile strlen
Writing or reading data into a file is basically divided into three steps:
1. Open a file (if present)
2. Write/Read files
3. Close this file
L Open File
Before opening a file, we need to know the path to the file and whether or not this file exists.
Use the $_server["Document_root"] to build a global variable to get the relative path of the site. As follows:
$root = $_server["Document_root"];
The function file_exists () is used 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 ');
fopen () function that accepts 2 or 3 or 4 parameters.
The first parameter is the file path, the second is the mode of operation (read/write/append, and so on), and the required parameters are selected.
$fp = fopen ("$root/order.txt", ' ab ');
The third is optional, and 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 option is also optional, allowing the file name to start with the protocol name (such as http://) and opening the file in a remote location, as well as supporting 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 are saved to the $FP variable.

Attached file pattern diagram


Write a file
Writing files in PHP is easier. Use the fwrite () function directly.
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 that $fp points to.
L Read files
1. Open files in read-only mode
The fopen () function is still used, but the file is opened in read-only mode, using the "RB" file mode. As follows:

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

while (!feof ($fp)) {
The information to process
}
3. Read one line of records at a time
The fgets () function reads a single line of content from a text file. As follows:

Copy Code code as follows:

$fp = fopen ("$root/order.txt", ' RB ');
while (!feof ($fp)) {
$info = fgets ($fp, 999);
echo $info. ' <br/> ';
}
Fclose ($FP);

In this way, he will read the data continuously until he reads a newline character (\ n) or a file terminator eof, or reads 998B from a file, and the maximum length that can be read is 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, and without echo. As follows:
ReadFile ("$root/order.txt");
It automatically prints 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 a file in Include_path, as in the fopen function, the return value is the total number of bytes read from the file.
Note: direct use without fopen or fclose
b). Fpassthru () function
To use this function, you must first open a file fopen (). The pointer to the file is then passed as a parameter to Fpassthru (), which outputs the contents of the file to which the file pointer points. 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 fopen and fclose
c). File () function
In addition to outputting the file to the browser, he and the ReadFile () function are the same, sending the results to an array. As follows:
$fileArray = File ("$root/order.txt");
Each row 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 directly outputting the contents of the file 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 one character
The FGETC () function reads one character at a time from a file, it has a file pointer function, which is also the only argument, and it returns the next character. As follows:
Copy Code code as follows:

$fp = fopen ("$root/order.txt", ' RB ');
while (!feof ($fp)) {
$char = fgetc ($FP);
if (!feof ($fp)) {
echo ($char = = "\ n"?) ' <br/> ': $char);
}
}
Fclose ($FP);

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

String Fread (resource fp,int length);
When you use this function, it either reads the number of bytes specified by the length parameter or reads the end of the file.
Copy Code code as follows:

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

L Close the file
Closing a file is simpler, calling the Fclose () function directly, and if it returns True, it 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 view 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 document reading and writing operations, I used to read this article after the basic operation of the document, issued here to share with you:
Read the file:
PHP Code:
Copy Code code as follows:

1. <?php
2.
3. $file _name = "Data.dat";
4.//The absolute path of the file to read: Homedata.dat
5.
6. $file _pointer = fopen ($file _name, "R");
7.//Open file, 8. "R" is a pattern, 9. Or how we're going to do it, 10. See details later in this article
11.
$file _read = fread ($file _pointer, FileSize ($file _name));
13.//through the document means 14. Pin Read File contents
15.
Fclose ($file _pointer);
17.//Close File
18.
The contents of the file read by "print" are: $file _read ";
20.//Display file contents
?>.
22.

Write file:
PHP Code:
Copy Code code as follows:

1. <?php
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 Back
9.
Fwrite ($file _pointer, "What You Wanna Write");
11.//First cut the file by 12. is 0 byte size, 13. And then write
14.
Fclose ($file _pointer);
16.//End
17.
Print "Data successfully written to file";
19.
?>
21st.

Append to File:
PHP Code:
Copy Code code as follows:

1. <?php
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 You Wanna Append");
10.//Not 11. Cut the file by 12. into 0 bytes, 13. Append data to File last
14.
Fclose ($file _pointer);
16.//End
17.
Print "Data was successfully appended to file";
19.
?>
21st.

The above is just a brief introduction, below we want to discuss some deeper.
There are times when multiple writes are occurring (most often in large traffic sites), resulting in useless data being written to files, such as:
The contents of the Info.file file 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 wrote Rob's information to the file, Bill was just about to write it, which was just to write the Rob Record ' n ', causing the file to be corrupted.
We certainly don't want this to happen, so let's look at file locking:
PHP Code:
Copy Code code as follows:

1. <?php
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 "The contents of the file is $file _read";
24.
?>
26.

In the example above, if two files read.php and read2.php have access to the file, they can all be read, but when a program needs to be written, it must wait until the read operation is complete and the file is released.
PHP Code:
Copy Code code as follows:

1. <?php
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 "W" mode is used to overwrite the file, I don't think it applies.
PHP Code:
Copy Code code as follows:

1. <?php
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. Use 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 appending data is a little different from other operations, which is fseek! It is always a good habit to confirm that the file pointer is at the end of the file.
If you are on a Windows system, the file name above should be preceded by a ".
Flock of the following topics:
Flock () is locked only when the file is open. After the file is opened before the lock, now the contents of the file is only at the current content, and does not reflect the results of other program operations, so not only in the file append operation, or read operation should also use Fseek.
(the translation may not be very exact here, but I want to mean it).
About Patterns:
' R '-read-only open, file pointer placed on file header
' r+ '-read-write mode open, file pointer placed on file header
' W '-write-only open, file pointer placed on file header, file cut to 0 bytes, if file does not exist, try to create file
' w+ '-read and write open, file pointer placed on file header, file size cut to 0 bytes, if file does not exist, try to create file
' A '-write-only mode open, file pointer at end of file, if file does not exist, try to create file
' A + '-read and write open, file pointer at end of file, if file does not exist, try to create file
By the way, the code that creates the file directory
Copy Code code as follows:

Create a similar ".. /.. /.. /xxx/xxx.txt "Directory
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",);
The original function uses $globals["Dirseparator"] I changed 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 documents on the operation of the code, I believe that the beginner is very useful, posted out here, hope to have the function!

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.