File read and write operation in PHP

Source: Internet
Author: User
Tags create directory explode flock fread mkdir php code
File read and write operation in PHP


PHP provides a series of I/O functions that simplify the functionality we need, including file system operations and directory operations (such as "Copying [Copy]"). The following is to introduce the basic file read and write operations: (1) Read the file, (2) write the file, (3) append to the file.

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:
1. <?php
2. &nbsp;
3. $file _name = "Data.dat";
4.//The absolute path of the file to read: Homedata.dat
5. &nbsp;
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
One. &nbsp;
$file _read = fread ($file _pointer, FileSize ($file _name));
13.//through the document means 14. Pin Read File contents
&nbsp;
Fclose ($file _pointer);
17.//Close File
&nbsp;
The contents of the file read by "print" are: $file _read ";
20.//Display file contents
?>.
&nbsp;

Write file:
PHP Code:
1. <?php
2. &nbsp;
3. $file _name = "Data.dat";
4.//absolute path: Homedata.dat
5. &nbsp;
6. $file _pointer = fopen ($file _name, "w");
7.//"W" is a mode, 8. See Back
9. &nbsp;
Fwrite ($file _pointer, "What You Wanna Write");
11.//First cut the file by 12.     is 0 byte size, 13. And then write
&nbsp;
Fclose ($file _pointer);
16.//End
&nbsp;
Print "Data successfully written to file";
&nbsp;
?>
&nbsp;

Append to File:
PHP Code:
1. <?php
2. &nbsp;
3. $file _name = "Data.dat";
4.//absolute path: Homedata.dat
5. &nbsp;
6. $file _pointer = fopen ($file _name, "a");
7.//"W" mode
8. &nbsp;
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
&nbsp;
Fclose ($file _pointer);
16.//End
&nbsp;
Print "Data was successfully appended to file";
&nbsp;
?>
&nbsp;

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:
1. <?php
2. &nbsp;
3. $file _name = "Data.dat";
4. &nbsp;
5. $file _pointer = fopen ($file _name, "R");
6. &nbsp;
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.
One. &nbsp;
if ($lock) {
&nbsp;
$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.
&nbsp;
19.}
&nbsp;
Fclose ($file _pointer);
&nbsp;
Print "The contents of the file is $file _read";
&nbsp;
?>
&nbsp;

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:
1. <?php
2. &nbsp;
3. $file _name = "Data.dat";
4. &nbsp;
5. $file _pointer = fopen ($file _name, "w");
6. &nbsp;
7. $lock = Flock ($file _pointer, LOCK_EX);
8.//If the version is below php4.0.2,9. Replace LOCK_EX with 2.
&nbsp;
One. if ($lock) {
&nbsp;
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.
&nbsp;
18.}
&nbsp;
Fclose ($file _pointer);
&nbsp;
Print "Data successfully written to file";
&nbsp;
?>
&nbsp;

Although "W" mode is used to overwrite the file, I don't think it applies.
PHP Code:
1. <?php
2. &nbsp;
3. $file _name = "Data.dat";
4. &nbsp;
5. $file _pointer = fopen ($file _name, "a");
6. &nbsp;
7. $lock = Flock ($file _pointer, LOCK_EX);
8.//If the version is below php4.0.2,9. Replace LOCK_EX with 2.
&nbsp;
One. if ($lock) {
&nbsp;
Fseek ($file _pointer, 0, seek_end);
14.//If the version is less than php4.0rc1,15. Use Fseek ($file _pointer, filsize ($file _name));
&nbsp;
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.
&nbsp;
22.}
&nbsp;
Fclose ($file _pointer);
&nbsp;
Print "Data successfully written to file";
&nbsp;
?>
&nbsp;

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

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.