Tips for using PHP fread of

  • 2020-03-31 20:15:55
  • OfStack

instructions
String fread (int handle, int length)
Fread () reads a maximum length of bytes from the file pointer handle. Depending on what happens first, this function stops reading the file after reading the maximum length of bytes, or when it reaches EOF, or (for network streams) when a package is available, or (after opening the user-space stream) when it has read 8192 bytes.
Returns the string read, or FALSE on an error.
 
<?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 (such as Windows) that distinguishes binary files from text files, the mode parameter of the fopen() function is added to 'b'.
 
<?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, such as a stream returned from a remote file or popen() and proc_open(), the reading stops after a package is available. This means that the data collection should be consolidated into chunks as shown in the following example.
 
<?php 
//For 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, use file_get_contents(), which performs much better than the code above.
Additional:
file_get_contents
(PHP 4 > = 4.3.0, PHP 5)
File_get_contents -- reads the entire file into a string
instructions
String file_get_contents (string filename [, bool use_include_path [, resource context [, int offset [, int maxlen]]])

Just like file(), except file_get_contents() reads the file into a string. Will start reading 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. Memory mapping techniques are also used to enhance performance if the operating system supports them.

Related articles: