fread

(PHP 4, PHP 5)

freadБинарно-безопасное чтение файла

Описание

string fread ( resource $handle , int $length )

fread() читает до length байт из файлового указателя handle. Чтение останавливается как только было достигнуто одно из следующих условий:

  • было прочитано length байт
  • достигнут EOF (конец файла)
  • стал доступен пакет или произошел таймаут сокета (для сетевых потоков)
  • если читаемый поток является буферизованным и не представляет собой обычный файл, то за один раз максимум читается количество байт, равное размеру одной порции данных (обычно это 8192), однако, в зависимости от ранее буферизованных данных размер возвращаемых данных может быть больше размера одной порции данных.

Список параметров

handle

Указатель (resource) на файл, обычно создаваемый с помощью функции fopen().

length

length указывает размер прочитанных данных в байтах.

Возвращаемые значения

Возвращает прочтенную строку или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Простой пример использования fread()

<?php
// получает содержимое файла в строку
$filename "/usr/local/something.txt";
$handle fopen($filename"r");
$contents fread($handlefilesize($filename));
fclose($handle);
?>

Пример #2 Пример бинарного чтения с помощью fread()

Внимание

На системах, которые различают бинарные и текстовые файлы (к примеру, Windows), файл должен быть открыт с использованием буквы 'b' в параметре mode функции fopen().

<?php
$filename 
"c:\\files\\somepic.gif";
$handle fopen($filename"rb");
$contents fread($handlefilesize($filename));
fclose($handle);
?>

Пример #3 Примеры удаленного чтения с помощью fread()

Внимание

При чтении чего-либо отличного от локальных файлов, например потоков, возвращаемых при чтении удаленных файлов или из popen() и fsockopen(), чтение остановится после того, как пакет станет доступным. Это означает, что вы должны собирать данные вместе по кусочкам, как показано на примере ниже.

<?php
// Для PHP 5 и выше
$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($handle8192);
}
fclose($handle);
?>

Примечания

Замечание:

Если вы просто хотите получить содержимое файла в виде строки, используйте file_get_contents(), так как эта функция намного производительнее, чем код описанный выше.

Замечание:

Учтите, что fread() читает начиная с текущей позиции файлового указателя. Используйте функцию ftell() для нахождения текущей позиции указателя и функцию rewind() для перемотки позиции указателя в начало.

Смотрите также

  • fwrite() - Бинарно-безопасная запись в файл
  • fopen() - Открывает файл или URL
  • fsockopen() - Открывет соединение с интернет сокетом или доменным сокетом Unix
  • popen() - Открывает файловый указатель процесса
  • fgets() - Читает строку из файла
  • fgetss() - Прочитать строку из файла и отбросить HTML-теги
  • fscanf() - Обрабатывает данные из файла в соответствии с форматом
  • file() - Читает содержимое файла и помещает его в массив
  • fpassthru() - Выводит все оставшиеся данные из файлового указателя
  • ftell() - Сообщает текущую позицию чтения/записи файла
  • rewind() - Сбрасывает курсор у файлового указателя

Коментарии

Fread is binary-safe IF AND ONLY IF you don't use magic-quotes. If you do, all null bytes will become \0, and you might get surprising results when unpacking.

That is, you would do something like

<?php
set_magic_quotes_runtime
(0);
?>

before fread()

and something like

<?php
set_magic_quotes_runtime
(get_magic_quotes_gpc()) after.
?>

And, after fread, an unpack would be needed, of course. Surprisingly, pack(), however, does not work quite like in Perl (or perhaps I'm just missing something here) - you can't pack an array directly, but instead you'll have to pack each element seperately to the string:

<?php
foreach ($data as $dec) {
 
$data_output .= pack("C*"$dec);
}
?>
2000-08-26 05:22:17
http://php5.kiev.ua/manual/ru/function.fread.html
Автор:
I spent a while trying to get this to work so I thought I'd share.

Here's how to read a remote binary file using fread.

<?php
$fp 
fopen("http://www.example.com/img.jpg""rb");

if(
$fp){
 while(!
feof($fp)) {
     
$img $img fread($fp1024);
 }
}
?>

This will read the contents of the file into the var $img 1024 bytes at a time.  I used that number because it seemed safe, but you can increment it all you want I guess.

I don't know if everyone but me gets this, but I thought I'd share since I didn't see anything like it out there.
2002-11-14 03:28:52
http://php5.kiev.ua/manual/ru/function.fread.html
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($fp1024);
       
$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($str0$pos);} else {$contents substr($str$startPos$pos $startPos);}
                   
$occurence 0;
                    break;
                }
               
$lastPos $pos 1;
            }
        }
    }
    @
fclose($fp);
    return 
$contents;
}
?>
2004-05-14 03:32:51
http://php5.kiev.ua/manual/ru/function.fread.html
After using the suggested function from Rasmus Schultz : mindplay(at)mindplay(dot)dk, I've just noticed that people trying to download big files with a slow connection would get download stopped after exactly 60seconds -> the max execution time set with php.ini.
I suggest using a bigger buffer (1024x1024), or maybe resetting the time limit within the 'while' cicle with:
   set_time_limit(0);

The cicle would go like this:

<?php
   
while(!feof($file) and (connection_status()==0)) { 
     print(
fread($file1024*1024)); 
     
set_time_limit(0);
     
flush(); 
   } 
?>

Frederico Pinho
2004-10-13 17:21:33
http://php5.kiev.ua/manual/ru/function.fread.html
If, like me, you're in the habit of using fopen("http://...") 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).
2004-12-01 16:23:01
http://php5.kiev.ua/manual/ru/function.fread.html
Here's a function for sending a file to the client - it may look more complicated than necessary, but has a number of advantages over simpler file sending functions:

- Works with large files, and uses only an 8KB buffer per transfer. 

- Stops transferring if the client is disconnected (unlike many scripts, that continue to read and buffer the entire file, wasting valuable resources) but does not halt the script 

- Returns TRUE if transfer was completed, or FALSE if the client was disconnected before completing the download - you'll often need this, so you can log downloads correctly. 

- Sends a number of headers, including ones that ensure it's cached for a maximum of 2 hours on any browser/proxy, and "Content-Length" which most people seem to forget. 

(tested on Linux (Apache) and Windows (IIS5/6) under PHP4.3.x)

Note that the folder from which protected files will be pulled, is set as a constant in this function (/protected) ... Now here's the function: 

<?php
function send_file($name) {
 
ob_end_clean();
 
$path "protected/".$name;
  if (!
is_file($path) or connection_status()!=0) return(FALSE);
 
header("Cache-Control: no-store, no-cache, must-revalidate");
 
header("Cache-Control: post-check=0, pre-check=0"false);
 
header("Pragma: no-cache");
 
header("Expires: ".gmdate("D, d M Y H:i:s"mktime(date("H")+2date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
 
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
 
header("Content-Type: application/octet-stream");
 
header("Content-Length: ".(string)(filesize($path)));
 
header("Content-Disposition: inline; filename=$name");
 
header("Content-Transfer-Encoding: binary\n");
  if (
$file fopen($path'rb')) {
    while(!
feof($file) and (connection_status()==0)) {
      print(
fread($file1024*8));
     
flush();
    }
   
fclose($file);
  }
  return((
connection_status()==0) and !connection_aborted());
}
?>

And here's an example of using the function: 

<?php 
if (!send_file("platinumdemo.zip")) { 
die (
"file transfer failed"); 
// either the file transfer was incomplete 
// or the file was not found 
} else { 
// the download was a success 
// log, or do whatever else 

?> 

Regards, 
Rasmus Schultz
2005-01-16 02:20:40
http://php5.kiev.ua/manual/ru/function.fread.html
To make the effects of the latest PHP version changes of the fread function even more explicit:  the new size limitation of fread -regardless of the filesize one specifies,  in the example below 1024 * 1024- means that if one was  simply reading the contents of a text file from a dynamic URL like so:

<?php
  $dp 
"http://www.example.com/filename.php";
 
$buffer fopen($dp'r');
  if (!
$buffer
    {
      echo(
"<P>Error: unable to load URL file into $buffer.      Process  aborted.</P>");
      exit();
    }
 
$sp fread($buffer1024*1024);
 
fclose($buffer);
 
highlight_string($sp);
?>

one should from now on use the file_get_contents function, as shown below, to avoid one's text being truncated forcibly.

<?php
  $dp 
"http://www.example.com/filename.php";
  if (!
$dp
    {
      echo(
"<P>Error: unable to load URL file into $dp.  Process aborted.</P>");
      exit();
    }
 
$sp file_get_contents($dp);
 
highlight_string($sp);
?>

I thought it couldn't hurt to clarify this detail in order to save time for anyone else who is in the same situation as I was tonight when my ISP abruptly upgraded to the latest version of PHP...    :(

Thank you to every previous contributor to this topic.
2005-03-05 04:59:56
http://php5.kiev.ua/manual/ru/function.fread.html
I was trying to implement resume support in download script, and i have finnaly succeded. here is the script:

<?php
function dl_file_resume($file){

   
//First, see if the file exists
   
if (!is_file($file)) { die("<b>404 File not found!</b>"); }

   
//Gather relevent info about file
   
$len filesize($file);
   
$filename basename($file);
   
$file_extension strtolower(substr(strrchr($filename,"."),1));

   
//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";
   }

   
//Begin writing headers
   
header("Pragma: public");
   
header("Expires: 0");
   
header("Cache-Control:");
   
header("Cache-Control: public"); 
   
header("Content-Description: File Transfer");
   
   
//Use the switch-generated Content-Type
   
header("Content-Type: $ctype");
$filespaces str_replace("_"" "$filename);

//if your filename contains underscores, you can replace them with spaces
 
$header='Content-Disposition: attachment; filename='.$filespaces.';';
   
header($header );
   
header("Content-Transfer-Encoding: binary");

 
$size=filesize($file);
//check if http_range is sent by browser (or download manager)
   
if(isset($_ENV['HTTP_RANGE'])) {
 list(
$a$range)=explode("=",$_ENV['HTTP_RANGE']);
//if yes, download missing part
 
str_replace($range"-"$range);
 
$size2=$size-1;
 
header("Content-Range: $range$size2/$size");
 
$new_length=$size2-$range;
 
header("Content-Length: $new_length");
/if 
notdownload whole file
} else {
 
$size2=$size-1;
 
header("Content-Range: bytes 0-$size2/$size");
 
header("Content-Length: ".$size2);
}
//open the file
$fp=fopen("$file","r");
//seek to start of missing part
fseek($fp,$range);
//start buffered download
while(!feof($fp))
{
//reset time limit for big files
set_time_limit();
print(
fread($fp,1024*8));
 
flush();
}
fclose($fp); 
   
   exit;
     

?>

EXAMPLE
<?php
dl_file_resume
("somefile.mp3");
?>

please write if you find any errors, i have tested this only with mp3 files, but others should be fine
2005-03-13 14:22:09
http://php5.kiev.ua/manual/ru/function.fread.html
Just a note for anybody trying to implement a php handled download script -

We spent a long time trying to figure out why our code was eating system resources on large files.. Eventually we managed to trace it to output buffering that was being started on every page via an include.. (It was attempting to buffer the entire 600 Megs or whatever size *before* sending data to the client) if you have this problem you may want to check that first and either not start buffering or close that in the usual way :)

Hope that prevents somebody spending hours trying to fix an obscure issue.

Regards :)
2005-04-07 22:02:54
http://php5.kiev.ua/manual/ru/function.fread.html
If you use any of the above code for downloadinng files, Internet Explorer will change the filename if it has multiple periods in it to something with square brackets.  To work around this, we check to see if the User Agent contains MSIE and rewrite the necessary periods as %2E

<?php
# eg. $filename="setup.abc.exe";
if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) { 
   
# workaround for IE filename bug with multiple periods / multiple dots in filename
    # that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe
   
$iefilename preg_replace('/\./''%2e'$filenamesubstr_count($filename'.') - 1);
   
header("Content-Disposition: attachment; filename=$iefilename);
} else {
   
header("Content-Disposition: attachment; filename=$filename");
}
?>
2005-07-01 00:11:10
http://php5.kiev.ua/manual/ru/function.fread.html
<?php
/*
geoCode($address)
Accepts an address in the form of
999 Geocode Dr. New York, Ny 10108
returns array with lat and lon
*/

function geoCode($address) {

   
$gaddress "http://maps.google.com?q=" urlencode($address);

   
$handle fopen($gaddress"r");
   
$contents '';

     while (!
feof($handle)) {
         
$contents .= fread($handle8192);
     }
     
fclose($handle);
     
ereg('<center lat="([0-9.-]{1,})" lng="([0-9.-]{1,})"/>'$contents$regs);

     
$returnData['lat'] = $regs[1];
     
$returnData['lon'] = $regs[2];

     return 
$returnData;
}

print_r(geoCode("1064 Georgetown ln. Birmingham, Al 35217"));
?>
2005-09-20 23:00:04
http://php5.kiev.ua/manual/ru/function.fread.html
Changing the value of $length may yield to different download speeds when serving a file from a script.

I was not able to max out my 10mbps connection when 4096 was used. I found out that using 16384 would use all the available bandwidth.

When outputing binary data with fread, do not assume that 4096 or 8192 is the optimal value for you. Do some benchmarks by downloading files through your script.
2007-03-28 00:20:49
http://php5.kiev.ua/manual/ru/function.fread.html
reading from a socket stream can be different to the
behaviour expected, since you have not set
stream_set_blocking to 1.
sample source:
<?php
$fp 
fsockopen ($server$port$errno$errstr$socket_timeout);
$header '';
do {
   
$header.=fread($fp,1);
   
$i++;
} while (!
preg_match('/\\r\\n\\r\\n$/'$header) && $i $maxheaderlenth);
preg_match('/Content\\-Length:\\s+([0-9]*)\\r\\n/'$header,$matches);
$buffer fread($this->_fp$matches[1]);
?>

if i.e. the content length is 50000 and the responding server is to slow
(means 50000 are not completely sent when fread is called) 
you'll only receive the number of bytes sent by the 
responding server at the time fread is called.

fread will not wait for any data to complete the given size.
as described in user notes on stream_set_blocking there 
seems to be a bug using stream_set_blocking.
a workaround - well, not the best way - is to read
the response split to 1 byte
instead of 
<?php $buffer fread($this->_fp$matches[1]); ?>

you'd write
<?php
$buffer 
'';
for(
$i 0$i $matches[1]; $i++){
   
$buffer .= fread($this->_fp1);
}
?>

it several tests this seems like it works.
2007-05-10 10:52:55
http://php5.kiev.ua/manual/ru/function.fread.html
I thought I had an issue where fread() would fail on files > 30M in size. I tried a file_get_contents() method with the same results. The issue was not reading the file, but echoing its data back to the browser. 

Basically, you need to split up the filedata into manageable chunks before firing it off to the browser:

<?php

$total     
filesize($filepath);
$blocksize = (<< 20); //2M chunks
$sent      0;
$handle    fopen($filepath"r");

// Push headers that tell what kind of file is coming down the pike
header('Content-type: '.$content_type);
header('Content-Disposition: attachment; filename='.$filename);
header('Content-length: '.$filesize 1024);
               
// Now we need to loop through the file and echo out chunks of file data
// Dumping the whole file fails at > 30M!
while($sent $total){
    echo 
fread($handle$blocksize);
   
$sent += $blocksize;
}
           
exit(
0);

?>

Hope this helps someone!
2007-10-10 13:32:42
http://php5.kiev.ua/manual/ru/function.fread.html
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($f5); //5 seconds read timeout
 
if (!fread($f5)) echo "Error while reading";
    else echo 
"Read ok";
 
fclose($f);
 }
?>
2008-04-12 09:22:17
http://php5.kiev.ua/manual/ru/function.fread.html
This is an hack I've done to download remote files with HTTP resume support. This is useful if you want to write a download script that fetches files remotely and then sends them to the user, adding support to download managers (I tested it on wget). To do that you should also use a "remote_filesize" function that you can easily write/find.

<?php
function readfile_chunked_remote($filename$seek 0$retbytes true$timeout 3) {
   
set_time_limit(0);
   
$defaultchunksize 1024*1024;
   
$chunksize $defaultchunksize;
   
$buffer '';
   
$cnt 0;
   
$remotereadfile false;

    if (
preg_match('/[a-zA-Z]+:\/\//'$filename))
       
$remotereadfile true;

   
$handle = @fopen($filename'rb');

    if (
$handle === false) {
        return 
false;
    }

   
stream_set_timeout($handle$timeout);
   
    if (
$seek != && !$remotereadfile)
       
fseek($handle$seek);

    while (!
feof($handle)) {

        if (
$remotereadfile && $seek != && $cnt+$chunksize $seek)
           
$chunksize $seek-$cnt;
        else
           
$chunksize $defaultchunksize;

       
$buffer = @fread($handle$chunksize);

        if (
$retbytes || ($remotereadfile && $seek != 0)) {
           
$cnt += strlen($buffer);
        }

        if (!
$remotereadfile || ($remotereadfile && $cnt $seek))
            echo 
$buffer;

       
ob_flush();
       
flush();
    }

   
$info stream_get_meta_data($handle);

   
$status fclose($handle);

    if (
$info['timed_out'])
        return 
false;

    if (
$retbytes && $status) {
        return 
$cnt;
    }

    return 
$status;
}
?>
2008-04-28 18:32:18
http://php5.kiev.ua/manual/ru/function.fread.html
Автор:
I couldn't get some of the previous resume scripts to work with Free Download Manager or Firefox.  I did some clean up and modified the code a little.

Changes:
1. Added a Flag to specify if you want download to be resumable or not
2. Some error checking and data cleanup for invalid/multiple ranges based on http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt
3. Always calculate a $seek_end even though the range specification says it could be empty... eg: bytes 500-/1234
4. Removed some Cache headers that didn't seem to be needed. (add back if you have problems)
5. Only send partial content header if downloading a piece of the file (IE workaround)

<?php

function dl_file_resumable($file$is_resume=TRUE)
{
   
//First, see if the file exists
   
if (!is_file($file))
    {
        die(
"<b>404 File not found!</b>");
    }

   
//Gather relevent info about file
   
$size filesize($file);
   
$fileinfo pathinfo($file);
   
   
//workaround for IE filename bug with multiple periods / multiple dots in filename
    //that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe
   
$filename = (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE')) ?
                 
preg_replace('/\./''%2e'$fileinfo['basename'], substr_count($fileinfo['basename'], '.') - 1) :
                 
$fileinfo['basename'];
   
   
$file_extension strtolower($path_info['extension']);

   
//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;
        default:   
$ctype='application/force-download';
    }

   
//check if http_range is sent by browser (or download manager)
   
if($is_resume && isset($_SERVER['HTTP_RANGE']))
    {
        list(
$size_unit$range_orig) = explode('='$_SERVER['HTTP_RANGE'], 2);

        if (
$size_unit == 'bytes')
        {
           
//multiple ranges could be specified at the same time, but for simplicity only serve the first range
            //http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt
           
list($range$extra_ranges) = explode(','$range_orig2);
        }
        else
        {
           
$range '';
        }
    }
    else
    {
       
$range '';
    }

   
//figure out download piece from range (if set)
   
list($seek_start$seek_end) = explode('-'$range2);

   
//set start and end based on range (if set), else set defaults
    //also check for invalid ranges.
   
$seek_end = (empty($seek_end)) ? ($size 1) : min(abs(intval($seek_end)),($size 1));
   
$seek_start = (empty($seek_start) || $seek_end abs(intval($seek_start))) ? max(abs(intval($seek_start)),0);

   
//add headers if resumable
   
if ($is_resume)
    {
       
//Only send partial content header if downloading a piece of the file (IE workaround)
       
if ($seek_start || $seek_end < ($size 1))
        {
           
header('HTTP/1.1 206 Partial Content');
        }

       
header('Accept-Ranges: bytes');
       
header('Content-Range: bytes '.$seek_start.'-'.$seek_end.'/'.$size);
    }

   
//headers for IE Bugs (is this necessary?)
    //header("Cache-Control: cache, must-revalidate");   
    //header("Pragma: public");

   
header('Content-Type: ' $ctype);
   
header('Content-Disposition: attachment; filename="' $filename '"');
   
header('Content-Length: '.($seek_end $seek_start 1));

   
//open the file
   
$fp fopen($file'rb');
   
//seek to start of missing part
   
fseek($fp$seek_start);

   
//start buffered download
   
while(!feof($fp))
    {
       
//reset time limit for big files
       
set_time_limit(0);
        print(
fread($fp1024*8));
       
flush();
       
ob_flush();
    }

   
fclose($fp);
    exit;
}

?>
2008-06-28 14:45:49
http://php5.kiev.ua/manual/ru/function.fread.html
Автор:
It might be worth noting that if your site uses a front controller with sessions and you send a large file to a user; you should end the session just before sending the file, otherwise the user will not be able to continue continue browsing the site while the file is downloading.
2008-09-18 09:46:12
http://php5.kiev.ua/manual/ru/function.fread.html
Автор:
This code is buggy
<?php
$contents 
'';
while (!
feof($handle)) {
 
$contents .= fread($handle8192);
}
?>
When you read a file whose size is a multiple of the readsize (8192 here), then the loop is executed when there are no more data to read. Here, the result of fread() is not checked, and so the instruction
<?php
$contents 
.= fread($handle8192
?>
is executed once with no data from fread(). In this very case, it is not important, but in some situation it could be harmful.

The good way to read a file block by block is :
<?php
while ( ($buf=fread$handle8192 )) != '' ) {
   
// Here, $buf is guaranted to contain data
   
$contents .= $buf;
}
if(
$buf===FALSE) {
    echo 
"THERE WAS AN ERROR READING\n";
}
?>
2008-10-27 06:50:27
http://php5.kiev.ua/manual/ru/function.fread.html
Автор:
Various scripts suggested here attempt to deliver a file for download to a client. Handling http protocol features such as HTTP_RANGE is not trivial; neither is handling flow control with the server, memory and time limits when the files are large.

An alternative is to let the web server can handle http by redirecting to the file in question. It's not uncommon e.g. http://www.apple.com/downloads/macosx/ does this.

A PHP script can do any checks needed (security, authentication, validate the file) and any other tasks before calling header("Location $urltofile"); 

I tested this with apache. Interrupt/resume download works. The server's mime type configuration will determine client behavior. For apache, if defaults in mime.types are not suitable, configuration directives for mod_mime could go in a .htaccess file in the directory of the file to download. If really necessary, these could even by written by the PHP script before it redirects.
2008-10-29 10:11:22
http://php5.kiev.ua/manual/ru/function.fread.html
Автор:
Tom, the idea for the examples below is to ensure the user has proper credentials before serving the file. With that security in mind, the suggestion of a 302 redirection seems like a risky idea. Anyone with a modicum of networking experience can run a TCP trace and see the 302 Redirect response, as it is actually a response received by the client browser; the browser then makes a subsequent http request for the URL provided in the Location header.  When that 302 response is captured by wireshark, the 'secret' location is then exposed and can be shared with anyone who wishes to bypass the authorization routines in the php.

The only way to secure this would be for the 302 Redirection response to include some kind of unique, per-request, expiring authorization token, either on the end of the url or in a set-cookie, that is then checked by an authorization module implemented within the hosting webserver. Otherwise, you're relegated to the methods described below.
2009-01-13 18:20:39
http://php5.kiev.ua/manual/ru/function.fread.html
I had a fread script that hanged forever (from php manual):

<?php
$fp 
fsockopen("example.host.com"80);
if (!
$fp) {
    echo 
"$errstr ($errno)<br />\n";
} else {
   
fwrite($fp"Data sent by socket");
   
$content "";
    while (!
feof($fp)) {  //This looped forever
       
$content .= fread($fp1024);
    }
   
fclose($fp);
    echo 
$content;
}
?>

The problem is that sometimes end of streaming is not marked by EOF nor a fixed mark, that's why this looped forever. This caused me a lot of headaches...
I solved it using the stream_get_meta_data function and a break statement as the following shows:

<?php
$fp 
fsockopen("example.host.com"80);
if (!
$fp) {
    echo 
"$errstr ($errno)<br />\n";
} else {
   
fwrite($fp"Data sent by socket");
   
$content "";
    while (!
feof($fp)) { 
       
$content .= fread($fp1024);
       
$stream_meta_data stream_get_meta_data($fp); //Added line
         
if($stream_meta_data['unread_bytes'] <= 0) break; //Added line
   
}
   
fclose($fp);
    echo 
$content;
}
?>

Hope this will save a lot of headaches to someone.

(Greetings, from La Paz-Bolivia)
2009-08-30 15:16:55
http://php5.kiev.ua/manual/ru/function.fread.html
Note to IIS admins:

When using PHP via the FastCGI ISAPI extension, there is a script timeout of approximately 1hr that cannot be adjusted. When using PHP via CGI, there is a script timeout that is based upon the value of the CGITimeout configuration option. This value must be set extremely high if you plan to serve large files. An explanation of how to configure this option can be found here: http://www.iisadmin.co.uk/?p=7 If you do not modify this setting you can expect the above scripts to fail silently once it has hit the default value (30 minutes in my case).
2010-05-05 09:27:40
http://php5.kiev.ua/manual/ru/function.fread.html
Somehow all code samples for downloads, described here, doesn't work right for me.
When I download a big file readfile or fread in b mode, the final file hasn't the same md5 like the originial.

Some tests helps me, finding a solution:

<?php
            $fp 
fopen($DownloadFile'rb');
            while ( 
$cline fgets($fp) )
            {
                print 
$cline;
            }
           
fclose($fp);
?>

Somehow, it's "binary safe" and deliver that file which are read. md5 original and download are the same.
2010-09-21 09:45:29
http://php5.kiev.ua/manual/ru/function.fread.html
Автор:
If you serve a file download over PHP with fread and print/echo and experience corrupted binary files, chances are the server still uses magic quotes and escapes the null bytes in your file. Although from 5.3.0 magic quotes are no longer supported, you might still encounter this problem. Try to turn them off by placing this code before using fread:

<?php
@ini_set('magic_quotes_runtime'0);
?>
2011-03-18 07:59:29
http://php5.kiev.ua/manual/ru/function.fread.html
Автор:
Concerning [problems with UTF-8 and] downloading Zip files I found that simply adding 3 lines of code before starting the fread to the buffer for delivery in all browsers solved the problem.

<?php
    ob_end_clean
();
   
ob_start();
   
header'Content-Type:' );
?>

... see where placed in the function below:

<?php
function readfile_chunked$filename$retbytes true ) {
   
$chunksize * (1024 1024); // how many bytes per chunk
   
$buffer '';
   
$cnt 0;
   
$handle fopen$filename'rb' );
    if ( 
$handle === false ) {
        return 
false;
    }
   
ob_end_clean(); //added to fix ZIP file corruption
   
ob_start(); //added to fix ZIP file corruption
   
header'Content-Type:' ); //added to fix ZIP file corruption
   
while ( !feof$handle ) ) {
       
$buffer fread$handle$chunksize );
       
//$buffer = str_replace("","",$buffer);
       
echo $buffer;
       
ob_flush();
       
flush();
        if ( 
$retbytes ) {
           
$cnt += strlen$buffer );
        }
    }
   
$status fclose$handle );
    if ( 
$retbytes && $status ) {
        return 
$cnt// return num. bytes delivered like readfile() does.
   
}
    return 
$status;
}
?>
2011-08-20 13:45:56
http://php5.kiev.ua/manual/ru/function.fread.html
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); 
   
   
// send the headers and data
   
header("Content-Length: " $data_size); 
   
header("Content-md5: " $md5_sum); 
   
header("Accept-Ranges: bytes");   
    if (
$partial_contentheader('Content-Range: bytes ' $offset '-' . ($offset $length) . '/' $file_size);
   
header("Connection: close");
   
header("Content-type: " $ctype);
   
header('Content-Disposition: attachment; filename=' $file_name);
    echo 
$buffer
   
flush(); 
}
?>
2011-12-27 06:35:52
http://php5.kiev.ua/manual/ru/function.fread.html
I write this script for download with resume suport
<?php
// If user click the download link
if(isset($_GET['filename'])){
       
// The directory of downloadable files
        // This directory should be unaccessible from web
       
$file_dir="/tmp/";
 
       
// Replace the slash and backslash character with empty string
        // The slash and backslash character can be dangerous
       
$file_name=str_replace("/"""$_GET['filename']);
       
$file_name=str_replace("\\"""$file_name);
 
       
// If the requested file is exist
       
if(file_exists($file_dir.$file_name)){
               
// Get the file size
               
$file_size=filesize($file_dir.$file_name);
               
// Open the file
               
$fh=fopen($file_dir.$file_name"r");
 
               
// Download speed in KB/s
               
$speed=5;
 
               
// Initialize the range of bytes to be transferred
               
$start=0;
               
$end=$file_size-1;
 
               
// Check HTTP_RANGE variable
               
if(isset($_SERVER['HTTP_RANGE']) &&
                       
preg_match('/^bytes=(\d+)-(\d*)/'$_SERVER['HTTP_RANGE'], $arr)){
 
                       
// Starting byte
                       
$start=$arr[1];
                        if(
$arr[2]){
                               
// Ending byte
                               
$end=$arr[2];
                        }
                }
 
               
// Check if starting and ending byte is valid
               
if($start>$end || $start>=$file_size){
                       
header("HTTP/1.1 416 Requested Range Not Satisfiable");
                       
header("Content-Length: 0");
                }
                else{
                       
// For the first time download
                       
if($start==&& $end==$file_size){
                               
// Send HTTP OK header
                               
header("HTTP/1.1 200 OK");
                        }
                        else{
                               
// For resume download
                                // Send Partial Content header
                               
header("HTTP/1.1 206 Partial Content");
                               
// Send Content-Range header
                               
header("Content-Range: bytes ".$start."-".$end."/".$file_size);
                        }
 
                       
// Bytes left
                       
$left=$end-$start+1;
 
     
}
?>
<html>
<head>
        <title>Home</title>
</head>
<body>
        <a href="index.php?filename=file.pdf">Download</a>
</body>
</html>
2013-01-31 12:00:35
http://php5.kiev.ua/manual/ru/function.fread.html
For anyone still trying to write an effective file downloader function/script, the work has been done for you in all the major servers including Apache & nginx.

Using the X-Sendfile header, you can do the following:

if ($user->isLoggedIn())
{
    header("X-Sendfile: $path_to_somefile_private");
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"$somefile\"");
}

Apache will serve the file for you while NOT revealing your private file path! Pretty nice. This works on all browsers/download managers and saves a lot of resources.

Documentation:
Apache module: https://tn123.org/mod_xsendfile/
Nginx: http://wiki.nginx.org/XSendfile
Lighttpd: http://blog.lighttpd.net/articles/2006/07/02/x-sendfile/

Hopefully this will save you many hours of work.
2013-12-13 01:59:44
http://php5.kiev.ua/manual/ru/function.fread.html
My script was based on example 3b, but used up 100% CPU when a timeout occurred that wasn't "seen". This is very bad. So here's my code, hoping this will help people out there with the same problem. Obviously first use $rPage = fsockopen(...) and fwrite($rPage,...) and such, after which:

    $sPage    = ''; // the page goes in here
    $iTimeout    = 5; // set the timeout in seconds
    stream_set_timeout($rPage,$iTimeout);
    stream_set_blocking($rPage,0);
    $fTimeout    = microtime(true);
    do {
        if (($sRead = fread($rPage,8192))!==false and strlen($sRead)) {
            $sPage    .= $sRead; }
        else {
            usleep(10000); } // 0.01 second
        $aInfo    = stream_get_meta_data($rPage); }
    while (!feof($rPage) and !$aInfo['timed_out'] and microtime(true)-$fTimeout<$iTimeout);
    fclose($rPage);
    // now simply decompress and unchunk $sPage, if need be

Above code will make sure the timeout is used, because this isn't always detected properly. In addition, the usleep() will keep the CPU in check.
2014-02-11 19:13:15
http://php5.kiev.ua/manual/ru/function.fread.html
Note that fread() will return '' (empty string) when a timeout occurs unlike socket_read() which returns false...
2014-07-07 23:52:03
http://php5.kiev.ua/manual/ru/function.fread.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <?php
   
require_once "person.class.php";
    require_once 
"schueler.class.php";
    require_once 
"lehrer.class.php";
   
//$p = new Person("Hans", "Wurst");
    //$p->ausgabe();

   
$s = new Schueler("Kevin""Mayer""FTET3");
   
$s->ausgabe();

     
Lehrer::$maxGehaltsStufe 16;     
   
$l = new Lehrer("Karl""Napf"13);
   
$l->ausgabe();
   
$l->befoerdern();
   
$l->ausgabe();
   
$l->befoerdern();
   
$l->ausgabe();
   
$l->befoerdern();
   
$l->ausgabe();
   
$l->befoerdern();
   
$l->ausgabe();
   
?>
</body>
</html>
2022-05-16 08:26:39
http://php5.kiev.ua/manual/ru/function.fread.html

    Поддержать сайт на родительском проекте КГБ