Fread () reads up to length bytes from a file pointer handle.
Description
string fread (int handle, int length)
Fread () reads up to length bytes from a file pointer handle. The function stops reading the file when it has read up to the maximum length of bytes, or when it reaches EOF, or (for a network stream) when a package is available, or when 8,192 bytes have been read (after opening a stream of user space), depending on which situation is encountered first.
Returns the read string if an error returns FALSE.
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 you open a file on a system that distinguishes between binary and text files (such as Windows), the mode parameter of the fopen () function is prefixed with ' B '.
The 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-trivial local file, such as when reading a stream returned from a remote file or Popen () and Proc_open (), the read stops after a package is available. This means that the data should be collected together into chunks as shown in the following example.
The code is as follows:
<?php//To PHP 5 and later $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 just want to read the contents of a file into a string, using file_get_contents (), it performs much better than the code above.
Extra:
file_get_contents
(PHP 4 >= 4.3.0, PHP 5)
File_get_contents--Reads the entire file into a string
description
String file_ Get_contents (string filename [, bool Use_include_path [, resource context [, int offset [, int maxlen]]])
and fi Le () just reads the file into a string except file_get_contents (). Reads the contents of length MaxLen at the position specified by the parameter offset. If it fails, file_get_contents () returns FALSE. The
file_get_contents () function is the preferred method for reading the contents of a file into a string. If operating system support also uses memory-mapping techniques to enhance performance.