[edit] Last updated: Fri, 15 Mar 2013
view this page in
fread
(PHP 4, PHP 5)
fread — Binary-safe file read
Description
$handle
, int $length
)
fread() reads up to
length
bytes from the file pointer
referenced by handle
. Reading stops as soon as one
of the following conditions is met:
-
length
bytes have been read - EOF (end of file) is reached
- a packet becomes available or the socket timeout occurs (for network streams)
- if the stream is read buffered and it does not represent a plain file, at most one read of up to a number of bytes equal to the chunk size (usually 8192) is made; depending on the previously buffered data, the size of the returned data may be larger than the chunk size.
Parameters
-
handle
-
A file system pointer resource that is typically created using fopen().
-
length
-
Up to
length
number of bytes read.
Return Values
Returns the read string or FALSE
on failure.
Examples
Example #1 A simple fread() example
<?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);
?>
Example #2 Binary fread() example
On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.
<?php
$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
Example #3 Remote fread() examples
When reading from anything that is not a regular local file, such as streams returned when reading remote files or from popen() and fsockopen(), reading will stop after a packet is available. This means that you should collect the data together in chunks as shown in the examples below.
<?php
// For PHP 5 and up
$handle = fopen("www.example.com/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
?>
<?php
$handle = fopen("www.example.com/", "rb");
$contents = '';
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
?>
Notes
Note:
If you just want to get the contents of a file into a string, use file_get_contents() as it has much better performance than the code above.
Note:
Note that fread() reads from the current position of the file pointer. Use ftell() to find the current position of the pointer and rewind() to rewind the pointer position.
See Also
- fwrite() - Binary-safe file write
- fopen() - Opens file or URL
- fsockopen() - Open Internet or Unix domain socket connection
- popen() - Opens process file pointer
- fgets() - Gets line from file pointer
- fgetss() - Gets line from file pointer and strip HTML tags
- fscanf() - Parses input from a file according to a format
- file() - Reads entire file into an array
- fpassthru() - Output all remaining data on a file pointer
- ftell() - Returns the current position of the file read/write pointer
- rewind() - Rewind the position of a file pointer
[edit] Last updated: Fri, 15 Mar 2013
If you read from a socket connection or any other stream that may delay when responsing but you want to set a timeout you can use stream_set_timeout():
<?php
$f = fsockopen("127.0.0.1", 123);
if ($f)
{
fwrite($f, "hello");
stream_set_timeout($f, 5); //5 seconds read timeout
if (!fread($f, 5)) echo "Error while reading";
else echo "Read ok";
fclose($f);
}
?>
If, like me, you're in the habit of using fopen("...") and fread for pulling fairly large remote files, you may find that the upgrade to PHP5 (5.0.2 on Win2000/IIS5) causes fread to top out at about 8035 bytes. PHP5 RC2 with identical php.ini settings did not exhibit this behaviour (I was using this for testing). Irritating for me because I was using simple_xml_load to load the file contents as XML, and the problem initially appeared to be that function.
Solution - swap over to file_get_contents or use the loop suggested on the documentation above (see Warning).
The following function retrieves a line in a file, regardless of its size, so you won't get an error if the file's size is beyond php's allowed memory limit (the string has to be below however), which is something i was needing for accessing a big log file generated by a webhost. Indexes start at 1 (so $line = 1 means the first line unlike arrays). If the file is small, it would be better to use "file()" however.
<?php
function strpos_count($haystack, $needle, $i = 0) {
while (strpos($haystack,$needle) !== false) {$haystack = substr($haystack, (strpos($haystack,$needle) + 1)); $i++;}
return $i;
}
function getLine($file,$line=1){
$occurence = 0;
$contents = '';
$startPos = -1;
if (!file_exists($file)) return '';
$fp = @fopen($file, "rb");
if (!$fp) return '';
while (!@feof($fp)) {
$str = @fread($fp, 1024);
$number_of_occurences = strpos_count($str,"\n");
if ($number_of_occurences == 0) {if ($start_pos != -1) {$contents .= $str;}}
else {
$lastPos = 0;
for ($i = 0; $i < $number_of_occurences; $i++){
$pos = strpos($str,"\n", $lastPos);
$occurence++;
if ($occurence == $line) {
$startPos = $pos;
if ($i == $number_of_occurences - 1) {$contents = substr($str, $startPos + 1);}
} elseif ($occurence == $line + 1) {
if ($i == 0) {$contents .= substr($str, 0, $pos);} else {$contents = substr($str, $startPos, $pos - $startPos);}
$occurence = 0;
break;
}
$lastPos = $pos + 1;
}
}
}
@fclose($fp);
return $contents;
}
?>
Another sample function that supports from/to range requests:
<?php
function download_file($file_name) {
if (!file_exists($file_name)) { die("<b>404 File not found!</b>"); }
$file_extension = strtolower(substr(strrchr($file_name,"."),1));
$file_size = filesize($file_name);
$md5_sum = md5_file($file_name);
//This will set the Content-Type to the appropriate setting for the file
switch($file_extension) {
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "mp3": $ctype="audio/mpeg"; break;
case "mpg":$ctype="video/mpeg"; break;
case "avi": $ctype="video/x-msvideo"; break;
//The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)
case "php":
case "htm":
case "html":
case "txt": die("<b>Cannot be used for ". $file_extension ." files!</b>"); break;
default: $ctype="application/force-download";
}
if (isset($_SERVER['HTTP_RANGE'])) {
$partial_content = true;
$range = explode("-", $_SERVER['HTTP_RANGE']);
$offset = intval($range[0]);
$length = intval($range[1]) - $offset;
}
else {
$partial_content = false;
$offset = 0;
$length = $file_size;
}
//read the data from the file
$handle = fopen($file_name, 'r');
$buffer = '';
fseek($handle, $offset);
$buffer = fread($handle, $length);
$md5_sum = md5($buffer);
if ($partial_content) $data_size = intval($range[1]) - intval($range[0]);
else $data_size = $file_size;
fclose($handle);
&nb