PHP file read and write operation learning

Source: Internet
Author: User
Tags flock fread
    1. Note The!== operator does not exist before 4.0.0-RC2

    2. if ($handle = Opendir ('/path/to/files ')) {

    3. echo "Directory handle: $handle \ n";
    4. echo "files:\n";

    5. while (false!== ($file = Readdir ($handle))) {
    6. echo "$file \ n";
    7. }
    8. while ($file = Readdir ($handle)) {
    9. echo "$file \ n";
    10. }

    11. Closedir ($handle);

    12. }
    13. ?>

Copy Code

Read the file:

    1. $file _name = "Data.dat";
    2. Absolute path of the file to read: Homedata.dat
    3. $file _pointer = fopen ($file _name, "R");
    4. 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
    5. $file _read = fread ($file _pointer, FileSize ($file _name));
    6. By means of document 14. Pin Read File contents
    7. Fclose ($file _pointer);
    8. Close File
    9. Print "The contents of the file read: $file _read";
    10. Show file contents
    11. ?>
Copy Code

Write file:

    1. $file _name = "Data.dat";
    2. Absolute path: Homedata.dat
    3. $file _pointer = fopen ($file _name, "w");
    4. "W" is a pattern, 8. See later
    5. Fwrite ($file _pointer, "What Do You Wanna Write");
    6. Cut the file 12 first. is 0 bytes in size, 13. Then write
    7. Fclose ($file _pointer);
    8. End
    9. Print "Data successfully written to file";
    10. ?>
Copy Code

Append to file after:

    1. $file _name = "Data.dat";

    2. Absolute path: Homedata.dat

    3. $file _pointer = fopen ($file _name, "a");

    4. "W" mode
    5. Fwrite ($file _pointer, "What Do You Wanna Append");
    6. Not 11. Cut the file by 12. into 0 bytes, 13. Append data to the end of the file
    7. Fclose ($file _pointer);
    8. End
    9. Print "Data successfully appended to file";
    10. ?>
Copy Code

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:

    1. $file _name = "Data.dat";
    2. $file _pointer = fopen ($file _name, "R");
    3. $lock = Flock ($file _pointer, lock_sh);
    4. I use 4.0.2,9. So use lock_sh,10. You may need to write 1 directly.
    5. if ($lock) {
    6. $file _read = fread ($file _pointer, FileSize ($file _name));
    7. $lock = Flock ($file _pointer, Lock_un);
    8. If the version is less than php4.0.2,17. Replace Lock_un with 3
    9. }
    10. Fclose ($file _pointer);
    11. Print "File content is $file _read";
    12. ?>
Copy Code

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.

    1. $file _name = "Data.dat";
    2. $file _pointer = fopen ($file _name, "w");
    3. $lock = Flock ($file _pointer, LOCK_EX);
    4. If the version is below php4.0.2,9. Replace LOCK_EX with 2
    5. if ($lock) {
    6. Fwrite ($file _pointer, "What U Wanna Write");
    7. Flock ($file _pointer, Lock_un);
    8. If the version is below php4.0.2,16. Replace Lock_un with 3
    9. }
    10. Fclose ($file _pointer);
    11. Print "Data successfully written to file";
    12. ?>
Copy Code

Although the "W" mode is used to overwrite the file, I don't think it applies.

    1. $file _name = "Data.dat";

    2. $file _pointer = fopen ($file _name, "a");
    3. $lock = Flock ($file _pointer, LOCK_EX);
    4. If the version is below php4.0.2,9. Replace LOCK_EX with 2

    5. if ($lock) {

    6. Fseek ($file _pointer, 0, seek_end);
    7. If the version is less than php4.0rc1,15. Using Fseek ($file _pointer, filsize ($file _name));

    8. Fwrite ($file _pointer, "What U Wanna Write");

    9. Flock ($file _pointer, Lock_un);
    10. If the version is below php4.0.2,20. Replace Lock_un with 3
    11. }
    12. Fclose ($file _pointer);
    13. Print "Data successfully written to file";
    14. ?>

Copy Code

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 the mode: ' R '-read-only open, the file pointer is placed in the file header ' r+ '-read and write mode open, the file pointer is placed 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 establish the file The file size is cut to 0 bytes, if the file does not exist, try to establish the file ' a '-write-only open, the file pointer is placed at the end of the file, if the file does not exist, try to establish a file ' A + '-read and write open, the file pointer is placed at the end of the file,

By the way, the code that creates the file directory

  1. Create a similar ". /.. /.. Directory of/xxx/xxx.txt "

  2. function Createdirs ($path, $mode = 0777)//mode 077
  3. {
  4. $dirs = explode ('/', $path);
  5. $pos = Strrpos ($path, ".");
  6. if ($pos = = = False) {//Note:three equal signs
  7. Not found, means path ends in a dir not file
  8. $subamount = 0;
  9. }
  10. else {
  11. $subamount = 1;
  12. }

  13. for ($c =0; $c < count ($dirs)-$subamount; $c + +) {

  14. $thispath = "";
  15. for ($cc =0; $cc <= $c; $CC + +) {
  16. $thispath. = $dirs [$cc]. ' /';
  17. }
  18. if (!file_exists ($thispath)) {
  19. Print "$thispath
  20. ";
  21. mkdir ($thispath, $mode); mkdir function Create directory
  22. }
  23. }
  24. }
  25. Calls such as Createdirs ("xxx/xxxx/xxxx",);

  26. Use $globals["Dirseparator" in the original function I changed it to '/'

  27. function Recur_mkdirs ($path, $mode = 0777)//mode 0777

  28. {
  29. $GLOBALS ["Dirseparator"]
  30. $dirs = Explode ($GLOBALS ["Dirseparator"], $path);
  31. $pos = Strrpos ($path, ".");
  32. if ($pos = = = False) {//Note:three equal signs
  33. Not found, means path ends in a dir not file
  34. $subamount = 0;
  35. }
  36. else {
  37. $subamount = 1;
  38. }
Copy Code

The above article, for beginners Reference, master drift over.

  • 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.