So here we come to the part that we care about most, which is the operation of the f dependent function. Basically most of the file operations are based on today’s learning these content, without saying much, let’s learn one by one to learn.

File to read

Fopen () opens the handle, fread() reads the contents, fclose() closes the handle, and you’re done.

$f = fopen('./test.txt', 'r+'); while (! feof($f)) { $contents = fread($f, 4); echo $contents, PHP_EOL; } / / Rain / / is / / fall / / ing / / / / / arou nd all, / / It / / alls/f/on / /... / /...

The second argument to the fopen() function is the permission we can operate on. This should be familiar to you, w is writable, r is readable, r+ is read and write open and point to the file header, a is append write.

model instructions
‘r’ Open in read-only mode, pointing the file pointer to the file header.
‘r+’ Open in read-write mode, pointing the file pointer to the file header.
‘w’ Opens in write mode, points the file pointer to the file header and truncates the file size to zero. If the file does not exist, try to create it.
‘w+’ Opens in read-write mode, points the file pointer to the file header and truncates the file size to zero. If the file does not exist, try to create it.
‘a’ Open in write mode, pointing the file pointer to the end of the file. If the file does not exist, try to create it.
‘a+’ Open in read-write mode, pointing the file pointer to the end of the file. If the file does not exist, try to create it.
‘x’ Creates and opens as a write, pointing the file pointer to the file header. If the file already exists, the fopen() call fails and returns FALSE, generating an E_WARNING level error message. If the file does not exist, try to create it. This is similar to specifying O_EXCL to the underlying open(2) system call The O_CREAT flag is equivalent.
‘x+’ Creates and opens as read/write, otherwise behaves as ‘x’.
‘c’ Only open the file for writing. If the file does not exist, it is created. If it exists, it will neither be truncated (as opposed to “w”) nor cause a call to the function to fail (as with “x”)
‘c+’ Open the file to read and write; Otherwise it behaves the same as “C”.

The second argument to the fread() function is the number of bytes to read at a time. You can see that in the test code we read in units of 4 bytes, so the contents of the file are printed out line by line in 4 bytes. Feof () determines whether the cursor pointer for the current file has been moved to the end.

A cursor

Now that we’re talking about cursors, let’s look at cursor-related operations.

while (! feof($f)) { $contents = fread($f, 1024); echo $contents, PHP_EOL; } // rewind($f); while (! feof($f)) { $contents = fread($f, 1024); echo $contents, PHP_EOL; } // Rain is falling all around, // It falls on field and tree, // It rains on the umbrella here, // And on the ships at sea.

After reading the contents using the top code, the cursor is already at the bottom. At this time, it cannot read the contents of the file by looping again. You need to use the rewind() function to reset the cursor.

Read a single character

rewind($f); while (($c = fgetc($f)) ! == false) { echo $c, PHP_EOL; } // R // a // I/n // I/s // f // a //...... / /...

The fgetc() function is used to read individual characters. This function is relatively simple, but it should be noted that if you use it to read Chinese, the effect is not good, because Chinese is 2 or 3 bytes per word, using this function to read the content will be garbled, we will have examples later.

Read a line

while (($c = fgets($f)) ! == false) { echo $c, PHP_EOL; } // Rain is falling all around, // It falls on field and tree, // It rains on the umbrella here, // And on the ships at sea.

The fgets() function is used to read the contents of a file line by line. This function is one of the more common and familiar functions.

Read the CSV file

// fgetcsv $f = fopen('./csv_test.csv', 'r'); while (($c = fgetcsv($f)) ! == false) { print_r($c); } // Array // ( // [0] => 49 // [1] => 20 // [2] => 0 // [3] => 42 // [4] => 5/10/2020 12:32:18 // ) // Array // ( // [0] => 50 // [1] => 21 // [2] => 0 // [3] => 74 // [4] => 5/10/2020 12:32:29 // ) // Array // ( // [0] => 51 // [1] => 22 / / [2] [3] = > / = > 0 "35.8 / / [4] = > 5/10/2020 12:32:38 / / / /... / /... fclose($f);

I won’t go into details about what CSV is. In my first project after graduation, there were a lot of small functions for manipulating CSV files. In other words, the fgetcsv() function was my first function for manipulating CSV files. It makes it easy to read CSVs in rows and parse them into arrays for us to manipulate. However, if it is an Excel file, we will exclude the first line of the title line. Of course, this depends on the actual situation of business development.

Read filtered HTML

// fgetss $f = fopen('./html_test.txt', 'r'); while (($c = fgetss($f)) ! == false) { echo $c, PHP_EOL; } // PHP Deprecated: Function fgetss() is deprecated fclose($f);

The fgetss() function, which filters out HTML code while reading a file, is deprecated.

Chinese reading problem

For Chinese reading, our main concern is the difference between Chinese characters and English characters in bytes. As mentioned above, Chinese will take up 3 bytes if it is UTF8 encoding format, and 2 bytes if it is GBK, etc. So if we use fread(), we need to use the corresponding encoding multiples to read, for example, our test file is UTF8 encoding, need to be read by three characters, we need to pass the parameter 6.

$f = fopen('./cn_test.txt', 'r+'); while (! feof($f)) { $contents = fread($f, 6); echo $contents, PHP_EOL; } // I this // do nothing // wild guest //, floating // floating waves // trace people //. // a � // is accessed //...... / /... while (! feof($f)) { $contents = fread($f, 1024); echo $contents, PHP_EOL; } // rewind($f); while (! feof($f)) { $contents = fread($f, 1024); echo $contents, PHP_EOL; } // I am not a stranger, floating around the world. // I was ordered to live on a famous mountain. It's not fair to play by ear. // See through the dust and trouble, what is leisure. // The flowing clouds sing poems. And with the white clouds. rewind($f); while (($c = fgetc($f)) ! == false) { echo $c, PHP_EOL; } // � // switch // /...... / /... rewind($f); while (($c = fgets($f)) ! == false) { echo $c, PHP_EOL; } // I am not a stranger, floating around the world. // I was ordered to live on a famous mountain. It's not fair to play by ear. // See through the dust and trouble, what is leisure. // The flowing clouds sing poems. And with the white clouds. fclose($f);

Why does the fread() function read the contents with gibberish in the middle? Because our newline character or according to the English code only one byte ah! The fgetc() function, on the other hand, gets() just fine.

Read the rest of the content

$f = fopen('./cn_test.txt', 'r+'); echo fgets($f), PHP_EOL; // I am not a stranger, floating around the world. echo fpassthru($f), PHP_EOL; // I was ordered to live on a famous mountain. It's not fair to play by ear. // See through the dust and trouble, what is leisure. // The flowing clouds sing poems. And with the white clouds. rewind($f);

In this test, we use fgets() to read a line and then use fpassthru() to read the rest of the file directly. That’s what the fpassthru() function does, which reads everything in the file after the cursor.

fseek($f, 3 * 14 + 1); echo fgets($f), PHP_EOL; // I was ordered to live on a famous mountain. It's not fair to play by ear.

There is also a fseek() function, which specifies the current position from which to start reading, which can also be considered part of the cursor operation.

rewind($f); fseek($f, 14 * 2 * 3 + 1); echo ftell($f), PHP_EOL; / / 85

The ftell() function is the remaining byte information of the returned file.

File handle information

print_r(fstat($f)); // Array // ( // [0] => 16777220 // [1] => 8708492112 // [2] => 33188 // [3] => 1 // [4] => 501 // [5] => 20 // [6] => 0  // [7] => 177 // [8] => 1603414680 // [9] => 1603414679 // [10] => 1603414679 // [11] => 4096 // [12] => 8 // [dev] => 16777220 // [ino] => 8708492112 // [mode] => 33188 // [nlink] => 1 // [uid] => 501 // [gid] => 20 // [rdev] => 0 // [size] => 177 // [atime] => 1603414680 // [mtime] => 1603414679 // [ctime] => 1603414679 // [blksize] => 4096 // [blocks] => 8 // )

The fstat() function does the same thing as the stat() function we discussed in the previous article, except that it takes a handle argument and returns information about the file to which it belongs. Stat () directly gives you the path to the file.

File truncation

$ftruncate($f, 14*2*3+4); echo fread($f, 8094), PHP_EOL; // I am not a stranger, floating around the world. // I was ordered to live on a famous mountain. It's not fair to play by ear. fclose($f);

The ftruncate() function truncates the contents of the file from the specified location. Here we only keep the first two lines, and the rest of the content is truncated. One thing to note about using this function is that it changes the contents of the original file.

Reads the file and enters it from the format

$f = fopen("users_test.txt", "r"); while ($userinfo = fscanf($f, "%s\t%s\t%s\n")) { print_r($userinfo); } // Array // ( // [0] => javier // [1] => argonaut // [2] => pe // ) // Array // ( // [0] => hiroshi // [1] => sculptor  // [2] => jp // ) // Array // ( // [0] => robert // [1] => slacker // [2] => us // ) // Array // ( // [0] => luigi // [1] => florist // [2] => it // ) fclose($f);

The fscanf() function formats the contents of the file based on what is passed in the second argument. Just like you would use the printf() function, except that it gets the data content from a read point of view. Tabs are used as delimiters to form a formatted array of results.

File content matching

var_dump(fnmatch('*fall[ing]*', file_get_contents('./test.txt'))); // bool(true)

The fnmatch() function determines whether the given content contains the rule specified in the first argument. It’s a bit like regular express-related functions, and it’s not for files, it’s for strings. However, its rule definition is based on the file operation matching rules found in Linux systems, which means that it is not a complete regular rule. As we often do in Linux, we look for information about a file: ll *.txt.

Process file read operation

What does this mean? Basically, we can execute a piece of operating system process code, get the result of it, and the stream will be returned to PHP as a file stream to form a file stream handle.

$handle = popen("/bin/ls", "r"); while(! feof($handle)){ echo fgets($handle); } pclose($handle); PHP // 2. Learn directory operations in PHP.PHP // 3. PHP // 4. Use the DirectIO file extension.PHP // 5. PHP // cn_test.txt // Cn_test.txt // Cn_test.txt // Cn_test.txt // Cn_test.txt // Cn_test.txt csv_test.csv // html_test.txt // test.txt // timg.jpeg // users_test.txt // write.txt

File is written to

File writing is relatively simple, so a little code introduction. And there are only three functions.

$f = fopen('write.txt', 'w'); $f = fopen('write.txt', 'w'); fwrite($f, "This is Test! \n"); fputs($f, "This is Test2!! \n"); $CSV = [[' id ', 'name], [1,' Zyblog], [2, 'hardcore project manager]]. foreach($csv as $v){ fputcsv($f, $v); } fclose($f); // This is Test! // This is Test2!! // id,name // 1,Zyblog // 2, hardcore project manager

Fwrite () is used to write to a file handle. Fputs () is an alias to fwrite(), and the two are one thing. The fputcsv() function writes the contents of the array to the file in the CSV format, and it has other arguments that allow it to change which symbol is used for the delimiter, which in this case is a comma.

File locking

$fp = fopen("/tmp/lock.txt", "w+"); If (flock ($fp, LOCK_EX)) {/ / type exclusive lock fwrite ($fp, "write data:". The date (' H: I: s'). "\ n"); if(! $argv[1]){ sleep(50); } fflush($fp); Flush buffer flock($fp, LOCK_UN) before releasing the lock; } else {echo "Can't get the lock, can't write!" ; } fclose($fp);

Lock a file so that no other operation can read it, which is often used when multiple threads or functions operate on a file at the same time. The second parameter to flock() sets read locks, write locks, and so on, and here we are using the LOCK_EX shared exclusive lock, which is a write lock. When we run this code, no other script will be able to write data for a long time. If a script is running on this file at the same time, it will also be stuck until the lock is released.

  • LOCK_SH obtains the shared lock (read program).
  • LOCK_EX obtains exclusive lock (written to program.
  • LOCK_UN releases locking (whether shared or exclusive).
  • If you don’t want flock() to block on locking, then LOCK_NB (not yet supported on Windows).

Fflush () is used to flush buffers, and this is what we talked about earlier on buffers in PHP, so you can go back and brush up on the control of output buffering in PHP. In file operations, you can use this function to immediately flush the contents of the buffer and write the contents to the specific file.

conclusion

Isn’t it exciting to learn so many functions all at once? By the end of this article, you will have learned how to manipulate these files native to PHP. Of course, understanding is only one thing, more or more to try to apply to their own projects.

Test code:

https://github.com/zhangyue0503/dev-blog/blob/master/php/202010/source/8.PHP function in the file system (3). The PHP

Reference documents:

https://www.php.net/manual/zh/ref.filesystem.php

Search for “Hardcore Project Manager” on all media platforms