Description
string fread ( int handle, int length )
fread() reads up to length bytes from the file pointer handle. This function is called after reading up to length bytes, or when EOF is reached, or (for network streams) when a packet is available, or (after opening a user space stream) 8192 bytes have been read. Will stop reading the file, depending on which condition is encountered first.
Returns the read string, or FALSE if an error occurs.
Copy code The code is as follows:
// 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
The fopen() function when opening a file on a system that distinguishes between binary files and text files (such as Windows) The mode parameter should be added with 'b'.
Copy code The code is as follows:
$filename = "c:\files\somepic. gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize ($filename));
fclose($handle);
? >
WARNING
When reading from anything that is not a normal local file, such as when reading from a remote file or a stream returned from popen() and proc_open(), the read will Stop after a package is available. This means that the data should be collected and merged into chunks as shown in the example below.
Copy the code The code is as follows:
// For PHP 5 and above
$handle = fopen("http://www.example.com/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
?> ;
$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, use file_get_contents(), its performance is much better than the above code.
Extra:
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]]]] )
Same as file(), except that file_get_contents() reads the file into a string. Contents of length maxlen will be read starting at the position specified by the offset parameter. On failure, 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 the operating system supports it, memory mapping technology will also be used to enhance performance.
http://www.bkjia.com/PHPjc/321192.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321192.htmlTechArticleDescription string fread ( int handle, int length ) fread() reads up to length bytes from the file pointer handle . This function reads up to length bytes or when EOF is reached...