Description
String fread (INT handle, int length)
Fread () reads a maximum of length bytes from the file pointer handle. This function can be read by a maximum of length bytes, or when it reaches the EOF, or (for network streams) when a package is available, or (after opening the user space Stream) when 8192 bytes have been read, the system stops reading files.
Returns the read string. If an error occurs, false is returned.
CopyCode The Code is as follows: <? PHP
// Get contents of a file into a string
$ Filename = "/usr/local/something.txt ";
$ Handle = fopen ($ filename, "R ");
$ Contents = fread ($ handle, filesize ($ filename ));
Fclose ($ handle );
?>
Warning
When a file is opened on a system that distinguishes binary files from text files (such as Windows), 'B' must be added to the mode parameter of the fopen () function '.Copy codeThe Code is as follows: <? PHP
$ Filename = "C: \ files \ somepic.gif ";
$ Handle = fopen ($ filename, "rb ");
$ Contents = fread ($ handle, filesize ($ filename ));
Fclose ($ handle );
?>
Warning
When reading from any non-normal local file, for example, when reading the stream returned from a remote file or popen () and proc_open (), the read will stop when a package is available. This means that the data should be collected and merged into large blocks as shown in the following example.Copy codeThe Code is as follows: <? PHP
// For PHP 5 and later versions
$ Handle = fopen ("http://www.example.com/", "rb ");
$ Contents = stream_get_contents ($ handle );
Fclose ($ handle );
?>
<? PHP
$ Handle = fopen ("http://www.example.com/", "rb ");
$ Contents = "";
While (! Feof ($ handle )){
$ Contents. = fread ($ handle, 8192 );
}
Fclose ($ handle );
?>
Note: If you want to read the content of a file into a string and use file_get_contents (), its performance is much better than the above Code.
Additional:
File_get_contents
(PHP 4> = 4.3.0, PHP 5)
File_get_contents -- read the entire file into a string
Description
String file_get_contents (string filename [, bool use_include_path [, resource context [, int offset [, int maxlen])
Like file (), only file_get_contents () can read the file into a string. The content with the length of maxlen will be read at the position specified by the offset parameter. If it fails, file_get_contents () returns false.
The file_get_contents () function is used to read the file content into a string. If the operating system supports it, the memory ing technology will be used to enhance the performance.