PHP Doku:: Liest Binärdaten aus einer Datei - function.fread.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzDateisystemrelevante ErweiterungenDateisystemDateisystem-Funktionenfread

Ein Service von Reinhard Neidl - Webprogrammierung.

Dateisystem-Funktionen

<<fputs

fscanf>>

fread

(PHP 4, PHP 5)

freadLiest Binärdaten aus einer Datei

Beschreibung

string fread ( resource $handle , int $length )

fread() liest bis zu length Bytes vom Dateizeiger handle. Das Lesen wird beendet, sobald eine der folgenden Bedingungen eintritt:

  • length Bytes wurden gelesen
  • Das Dateiende (EOF, end of file) wurde erreicht
  • Ein Paket wird verfügbar (Bei Netzwerk-Streams)
  • 8192 Bytes wurden gelesen (nachdem ein Userspace-Stream geöffnet wurde)

Parameter-Liste

handle

Eine Dateisystemressource (resource), wie sie in der Regel von fopen() zurückgegeben wird.

length

Bis zu length Bytes lesen.

Rückgabewerte

Gibt die ausgelesene Zeichenkette zurück. Im Fehlerfall wird FALSE zurückgegeben.

Beispiele

Beispiel #1 Ein einfaches fread()-Beispiel

<?php
// liest den Inhalt einer Datei in einen String
$filename "/usr/local/etwas.txt";
$handle fopen($filename"r");
$contents fread($handlefilesize($filename));
fclose($handle);
?>

Beispiel #2 Ein fread()-Beispiel mit einer Binärdatei

Warnung

Auf Systemen, welche zwischen Binär- und Textdateien (z.B. Windows) unterscheiden, muss die Datei mit 'b' im fopen() Mode-Parameter geöffnet werden.

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

Beispiel #3 fread()-Beispiele für entfernte Dateien

Warnung

Wenn aus etwas gelesen werden soll, was keine normale lokale Datei ist, wie etwa Streams von entfernten Dateien oder von popen() und fsockopen(), so wird das Lesen beendet sobald ein Paket verfügbar ist. Das bedeutet, dass man die Daten in Stücken sammeln muss. Dies wird im unteren Beispiel gezeigt.

<?php
// Für PHP5 und höher
$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);
?>

Anmerkungen

Hinweis:

Wenn man nur den Inhalt einer Datei in eine Zeichenkette lesen will, so sollte man file_get_contents() verwenden, da dies eine bessere Performance hat als der obige Code.

Hinweis:

Beachten Sie, dass fread() an der aktuellen Position im Dateizeiger zu lesen beginnt. Verwenden Sie ftell(), um herauszufinden wo dieser Zeiger steht und die Funktion rewind(), um den Zeiger zurückzustellen.

Siehe auch

  • fwrite() - Schreibt Binärdaten in eine Datei
  • fopen() - Öffnet eine Datei oder URL
  • fsockopen() - Stellt eine Internet- oder Unix-Domain-Socket-Verbindung her
  • popen() - Öffnet einen Prozesszeiger
  • fgets() - Liest eine Zeile von der Position des Dateizeigers
  • fgetss() - Liest eine Zeile von der Position des Dateizeigers und entfernt HTML Tags.
  • fscanf() - Interpretiert den Input einer Datei entsprechend einem angegebenen Format
  • file() - Liest eine komplette Datei in ein Array
  • fpassthru() - Gibt alle verbleibenden Daten eines Dateizeigers direkt aus.
  • ftell() - Ermittelt die aktuelle Position des Dateizeigers
  • rewind() - Setzt den Dateizeiger auf das erste Byte der Datei


51 BenutzerBeiträge:
- Beiträge aktualisieren...
ricardsss at gmail dot com
4.01.2011 7:13
Simple userlist script that reads content from a file and prints it back.

<?php

    $file
= "users.txt";
   
$handle = fopen($file, "a+");
   
   
   
    if(!
filesize($file)>0) {
        echo
"File is empty!";
    }
    else {
       
$fcontent = fread($handle, filesize($file));
       
echoUsers();
    }
   
   
fclose($handle);
   
    function
echoUsers() {
        global
$fcontent;
       
$users = explode(" ", $fcontent);
       
        foreach(
$users as $user) {
            echo
$user."<br />";
        }
    }
   

   
?>
Anonymous
1.10.2010 15:25
Stream editor on php

#/bin/php
<?php
if (ftell(STDIN) !== 0) {
   
fwrite(STDERR, "Pipe error\n");
    exit(
1);
}
$input = '';
while (
true) {
   
$input = trim(fread(STDIN,10240));
    if (
feof(STDIN)) break;
    if (
$input === false || strlen($input) === 0) {
        continue;
    }
   
// replase '<br />' to 'newline'
   
$input = preg_replace('/<br\s*\/>/', "\n\t", $input);
   
fwrite(STDOUT, $input . "\n");
}
?>

Example:
cat some.html | this_script.php | grep something

Keyword list: pipe, tail, grep, sed
NOopensourceSPAM at prodigy7 dot de
21.09.2010 15:45
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.
anon
19.08.2010 17:09
Simple function for getting FTP file contents without all the messy FTP connect scripts.

<?php
function ftp_get_contents($username,$password,$server,$file) {
   
$login = "ftp://".$username.":".$password."@".$server."/".$file;
   
$handle = fopen($login, "rb");
    return
stream_get_contents($handle);
   
fclose($handle);
}
?>
david at identd dot dyndns dot org
5.05.2010 15:27
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).
Tblue
2.01.2010 2:29
Note that fread() returns an empty string if you try to read beyond EOF, while the manual states otherwise ("Returns [...] FALSE on failure."). This e. g. happens with empty files (0 bytes long).

This does not look like a bug in PHP's fread() implementation to me, but rather like a documentation bug. The manpage for the C function fread() states:
> fread() does not distinguish between end-of-file and error, and callers must use feof(3) and ferror(3) to determine which occurred.
It also says:
> If an error occurs, or the end-of-file is reached, the return value is a short item count (or zero).

That means that in the case of empty files, C's fread() returns 0 and thus we get an empty PHP string: PHP's fread() does not seem to check for errors as the manpage recommends; that's fine, the PHP programmer has to do it, but it would be nice if this behaviour would be explicitly documented.

In short: When using fread(), you have to check for FALSE and empty strings. Consider the following wrapper function:
<?php
function my_fread( $handle, $length )
{
  if( (
$ret = fread( $handle, $length ) ) === '' )
  {
    return
false;
  }

  return
$ret;
}
?>
edgarinvillegas at hotmail dot com
30.08.2009 21:16
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($fp, 1024);
    }
   
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($fp, 1024);
       
$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)
jordan314 at yahoo dot com
2.04.2009 22:46
I had trouble getting PHP and fread to serve mp3s to an iphone using quicktime/mobilesafari until I included all of these headers and their appropriate values:
Last-Modified:
ETag:
Accept-Ranges: bytes
Content-Length:
Connection: close
Content-Type: audio/mpeg

It worked with other browsers without Last-Modified and Etag, but the iphone required them.
James Ranson
14.01.2009 1:20
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.
tom
29.10.2008 17:11
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.
Anonymous
27.10.2008 13:50
This code is buggy
<?php
$contents
= '';
while (!
feof($handle)) {
 
$contents .= fread($handle, 8192);
}
?>
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($handle, 8192)
?>
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( $handle, 8192 )) != '' ) {
   
// Here, $buf is guaranted to contain data
   
$contents .= $buf;
}
if(
$buf===FALSE) {
    echo
"THERE WAS AN ERROR READING\n";
}
?>
Anonymous
18.09.2008 15:46
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.
Edward Jaramilla
28.06.2008 20:45
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_orig, 2);
        }
        else
        {
           
$range = '';
        }
    }
    else
    {
       
$range = '';
    }

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

   
//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))) ? 0 : 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 > 0 || $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($fp, 1024*8));
       
flush();
       
ob_flush();
    }

   
fclose($fp);
    exit;
}

?>
mail at 3v1n0 dot net
29.04.2008 0:32
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 != 0 && !$remotereadfile)
       
fseek($handle, $seek);

    while (!
feof($handle)) {

        if (
$remotereadfile && $seek != 0 && $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;
}
?>
shocker at shockingsoft dot com
12.04.2008 15:22
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);
 }
?>
daniel winter
7.01.2008 21:42
If you are sending binary data to the browser (ie: a file download) be sure to disable multibyte encoding!

mb_http_output("pass");

Took me a day to work out why my downloads were failing half-way through!
matt at matt-darby dot com
10.10.2007 19:32
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 = (2 << 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!
Blagovest Buyukliev
3.09.2007 13:45
Having tried to reliably transfer large amounts of binary data over a latent network, I found out that fread()/fwrite() should never be trusted to read/write the whole block with the exact length specified, even in blocking mode, even for small block lengths.

I came up with these two functions, fully-replaceable and reliable alternatives of fread()/fwrite() in a socket context:

<?php

function fullwrite ($sd, $buf) {
 
$total = 0;
 
$len = strlen($buf);

  while (
$total < $len && ($written = fwrite($sd, $buf))) {
   
$total += $written;
   
$buf = substr($buf, $written);
  }

  return
$total;
}

function
fullread ($sd, $len) {
 
$ret = '';
 
$read = 0;

  while (
$read < $len && ($buf = fread($sd, $len - $read))) {
   
$read += strlen($buf);
   
$ret .= $buf;
  }

  return
$ret;
}

?>

The functions are "greedy", i.e. trying to read/write as much data as possible at once. If the call to fread()/fwrite() reads/writes less than expected, then the next iteration eats up the remainder. Very smart as only the largest possible chunks are read/written.

Only in case of a broken pipe fullread()/fullwrite() return less than the specified length. Otherwise it is guaranteed that upon termination

strlen(fullread($sd, $len)) == $len

and

fullwrite($sd, $buf) == strlen($buf)

Works perfectly with a socket descriptor returned from stream_socket_client() or fsockopen().

Greetings from Rousse, Bulgaria.
kai at froghh dot de
10.05.2007 16:52
reading from a socket stream can be different to the
behaviour expected, since you have not set
stream_set_blocking to 1.
sample source:
$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
$buffer = fread($this->_fp, $matches[1]);

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

it several tests this seems like it works.
aubfre at hotmail dot com
28.03.2007 7:20
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.
eggbird at bigfoot dot com
14.03.2007 18:23
Since a fairly recent php (at least it's the case on 5.2.1), fread's memory behaviour changed.

I used to be able to do things like

<?php
$s
= fread($fp, 23985798219384);
?>

to read an entire file, as long as I was sure the file would not be more than 23985798219384 bytes long. This worked like a charm (and as documented), but since recently, PHP tries to allocate 23985798219384 bytes no matter what. So, if you get memory allocation errors, replace such code by something like

<?php
$s
= fread($fp, filesize($f));
?>

or even

<?php
$s
= file_get_contents($f);
?>

.
tchapin at gmail dot com
30.01.2007 23:27
<?php
// Usage: <a href="download.php?file=test.txt&category=test">Download</a> 
// Path to downloadable files (will not be revealed to users so they will never know your file's real address)
$hiddenPath = "secretfiles/";

// VARIABLES
if (!empty($_GET['file'])){
   
$file = str_replace('%20', ' ', $_GET['file']);
   
$category = (!empty($_GET['category'])) ? $_GET['category'] . '/' : '';
}
$file_real     = $hiddenPath . $category . $file;
$ip            = $_SERVER['REMOTE_ADDR'];

// Check to see if the download script was called
if (basename($_SERVER['PHP_SELF']) == 'download3.php'){
    if (
$_SERVER['QUERY_STRING'] != null){
       
// HACK ATTEMPT CHECK
        // Make sure the request isn't escaping to another directory
       
if (substr($file, 0, 1) == '.' || strpos($file, '..') > 0 || substr($file, 0, 1) == '/' || strpos($file, '/') > 0){
           
// Display hack attempt error
           
echo("Hack attempt detected!");
            die();
        }
       
// If requested file exists
       
if (file_exists($file_real)){
           
// Get extension of requested file
           
$extension = strtolower(substr(strrchr($file, "."), 1));
           
// Determine correct MIME type
           
switch($extension){
                case
"asf":     $type = "video/x-ms-asf";                break;
                case
"avi":     $type = "video/x-msvideo";               break;
                case
"exe":     $type = "application/octet-stream";      break;
                case
"mov":     $type = "video/quicktime";               break;
                case
"mp3":     $type = "audio/mpeg";                    break;
                case
"mpg":     $type = "video/mpeg";                    break;
                case
"mpeg":    $type = "video/mpeg";                    break;
                case
"rar":     $type = "encoding/x-compress";           break;
                case
"txt":     $type = "text/plain";                    break;
                case
"wav":     $type = "audio/wav";                     break;
                case
"wma":     $type = "audio/x-ms-wma";                break;
                case
"wmv":     $type = "video/x-ms-wmv";                break;
                case
"zip":     $type = "application/x-zip-compressed";  break;
                default:       
$type = "application/force-download";    break;
            }
           
// Fix IE bug [0]
           
$header_file = (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE')) ? preg_replace('/\./', '%2e', $file, substr_count($file, '.') - 1) : $file;
           
// Prepare headers
           
header("Pragma: public");
           
header("Expires: 0");
           
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
           
header("Cache-Control: public", false);
           
header("Content-Description: File Transfer");
           
header("Content-Type: " . $type);
           
header("Accept-Ranges: bytes");
           
header("Content-Disposition: attachment; filename=\"" . $header_file . "\";");
           
header("Content-Transfer-Encoding: binary");
           
header("Content-Length: " . filesize($file_real));
           
// Send file for download
           
if ($stream = fopen($file_real, 'rb')){
                while(!
feof($stream) && connection_status() == 0){
                   
//reset time limit for big files
                   
set_time_limit(0);
                    print(
fread($stream,1024*8));
                   
flush();
                }
               
fclose($stream);
            }
        }else{
           
// Requested file does not exist (File not found)
           
echo("Requested file does not exist");
            die();
        }
    }
}
?>
Dhani dot Novan at gmail dot com
3.04.2006 12:57
Better version from dl_file_resume
i just compile from past post notes here

Change:
1. Fix Critical BUG : (file exe will corrupt because the size is minus one)
before: header("Content-Length: ".$size2);
after: header("Content-Length: ".$size);

2. closequote filename
before: header("Content-Disposition: attachment; filename=$filename");
after: header("Content-Disposition: attachment; filename=\"$filename\"");

3. read as binary
before: $fp=fopen("$file","r");
after: $fp=fopen("$file","rb");

4. use ob_flush

5. workaround for IE filename bug

<?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;
        default:
$ctype="application/force-download";
    }
   
   
//Begin writing headers
   
header("Cache-Control:");
   
header("Cache-Control: public");
   
   
//Use the switch-generated Content-Type
   
header("Content-Type: $ctype");
    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', $filename, substr_count($filename, '.') - 1);
       
header("Content-Disposition: attachment; filename=\"$iefilename\"");
    } else {
       
header("Content-Disposition: attachment; filename=\"$filename\"");
    }
   
header("Accept-Ranges: bytes");
   
   
$size=filesize($file);
   
//check if http_range is sent by browser (or download manager)
   
if(isset($_SERVER['HTTP_RANGE'])) {
        list(
$a, $range)=explode("=",$_SERVER['HTTP_RANGE']);
       
//if yes, download missing part
       
str_replace($range, "-", $range);
       
$size2=$size-1;
       
$new_length=$size2-$range;
       
header("HTTP/1.1 206 Partial Content");
       
header("Content-Length: $new_length");
       
header("Content-Range: bytes $range$size2/$size");
    } else {
       
$size2=$size-1;
       
header("Content-Range: bytes 0-$size2/$size");
       
header("Content-Length: ".$size);
    }
   
//open the file
   
$fp=fopen("$file","rb");
   
//seek to start of missing part
   
fseek($fp,$range);
   
//start buffered download
   
while(!feof($fp)){
       
//reset time limit for big files
       
set_time_limit(0);
        print(
fread($fp,1024*8));
       
flush();
       
ob_flush();
    }
   
fclose($fp);
    exit;
}
?>
yellow1912 at yahoo dot com
1.02.2006 20:46
I tried to use the download resume script below, but it put extreme load on the server for just 1 download only (the file is around 200MB).

Be carefull when you test the script on your server. I'll fgets, or other functions and see if it works.
junk at gieson dot com
14.01.2006 23:40
To force download an mp3 file and/or prevent the mp3 from ending up in the browser's cache. This is very similiar to mindplay's example below.

<?php
@ob_end_clean();
// Only allow mp3 files
$allowedFileType = "mp3";

// Set the filename based on the URL's query string
$theFile = $_REQUEST['theFile'];

// Get info about the file
$f = pathinfo($theFile);

// Check the extension against allowed file types
if(strtolower($f['extension']) != strtolower($allowedFileType)) exit;

// Make sure the file exists
if (!file_exists($theFile)) exit;

// Set headers
header("Pragma: public");
header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: private");
header("Content-Transfer-Encoding: binary");
header("Content-Type: audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3");
// This line causes the browser's "save as" dialog
header( 'Content-Disposition: attachment; filename="'.$f['basename'].'"' );
// Length required for Internet Explorer
header("Content-Length: ".@urldecode(@filesize($theFile)));

// Open file
if (($f = fopen($theFile, 'rb')) === false) exit;

// Push file
while (!feof($f)) {
    echo
fread($f, (1*(1024*1024)));
   
flush();
    @
ob_flush();
}

// Close file
fclose($f);
exit;

?>
xjust at 3axe dot com
28.09.2005 10:06
i fixed the resume download function since there were few bugs in it. here it goes

changes:
- i added "partial content" header
- added "bytes" to the first content-range header
- changed _ENV to _SERVER on HTTP_RANGE

best regards from xjust.

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("Accept-Ranges: bytes");
//   header("Content-Transfer-Encoding: binary");

  $size=filesize($file);
//check if http_range is sent by browser (or download manager)
    if(isset($_SERVER['HTTP_RANGE'])) {
 list($a, $range)=explode("=",$_SERVER['HTTP_RANGE']);
//if yes, download missing part
 str_replace($range, "-", $range);
 $size2=$size-1;
 $new_length=$size2-$range;
 header("HTTP/1.1 206 Partial Content");
 header("Content-Length: $new_length");
 header("Content-Range: bytes $range$size2/$size");
} 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(0);
print(fread($fp,1024*8));
 flush();
}
fclose($fp);
  
   exit;
    
}
adamgamble at gmail dot com
21.09.2005 5:00
/*
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($handle, 8192);
     }
     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"));
Richard Dale richard at premiumdata dot n dot e dot t
1.07.2005 6:11
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

<?
# 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', $filename, substr_count($filename, '.') - 1);
   
header("Content-Disposition: attachment; filename=$iefilename" );
} else {
   
header("Content-Disposition: attachment; filename=$filename");
}
?>
admin at rainer-schuetze dot de
14.06.2005 15:25
According: dvsoftware at gmail dot com

Hi all, the sript by dvsoftware is quit handy. But I had a lot of problems to read the dam.. file. Every file. I was using a Windows Platform, maybe that was the mistake.
Annyway, I had to read the file in one session:

<?
:
:

        while(!
feof($fp))
        {
               
//print (fread($fp,1024*8)); //4096 //1024*8
               
print fread($fp,$size);
               
flush();
        }
       
fclose($fp);
:
:
?>
sheyh[at]nospam[]sheyh[dot]nospam[]com
20.04.2005 1:39
Following code which was given as official example can lead to infinite loop.
In case of running from command line and there is no Internet connection, fopen will fail by script timeout, however after that "!feof($handle)" will never be true.

The result will be script displaying infinite warnings and taking 10-20% cpu and it will not stop unless killed.

<?php
$handle
= fopen("http://www.example.com/", "r");
$contents = '';
while (!
feof($handle)) {
 
$contents .= fread($handle, 8192);
}
fclose($handle);
?>

I belive correct example should be:

<?php
$handle
= fopen("http://www.example.com/", "r");
$contents = '';
if(
$handle)
{
 while (!
feof($handle)) {
  
$contents .= fread($handle, 8192);
 }
fclose($handle);
}
?>
james at reflexive dot net
19.04.2005 20:34
Several of these examples use a Content-Disposition header to force the browser to save a file but then they specify the file name without quotes. This will cause problems for some browsers (Mozilla Fire Fox) if the file name contains a space.  You must put quotes around the name if you want to work reliably for all files in all browsers.
<?php
header
("Content-Disposition: attachment; filename=$theFileName"); // bad

header ("Content-Disposition: attachment; filename=\"$theFileName\""); // good

?>
planetiss at gmail dot com
8.04.2005 14:38
For download the big files (more than 8MB), you must used ob_flush() because the function flush empty the Apache memory and not PHP memory.
And the max size of PHP memory is 8MB, but ob_flush is able to empty the PHP memory.

header('Content-Type: application/force-download');
header ("Content-Length: " . filesize($file));
header ("Content-Disposition: attachment; filename=$theFileName");

   $fd = fopen($file, "r");
   while(!feof($fd))
  {
       echo fread($fd, 4096);
       ob_flush();
      
   }
mrhappy[at]dotgeek.org
8.04.2005 4:02
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 :)
james at reflexive dot net
17.03.2005 19:22
You will probably want to call unpack() if you are trying to read binary data out of a file and you want to interpret the data you read (rather than just passing it through to a browser). For example, if you were reading the header if a binary file format such as a BMP image file you would need to read 4 byte integers out of the binary file.  fread() will return the binary data in a string.  unpack() will let you extract data out of the string an use it as a number. 
<?php
function Read32BitLittleEndianIntFromBinaryFile($FileHandle)
{
   
$BinaryData = fread($FileHandle, 4);
   
$UnpackedData = unpack("V", $BinaryData);
    return
$UnpackedData[1];
}
?>
dvsoftware at gmail dot com
13.03.2005 21:22
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
not, download 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
fenris_wolf0 at yahoo dot com
5.03.2005 11:59
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:

<?
  $dp
= "http://www.whatever.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($buffer, 1024*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.

<?
  $dp
= "http://www.whatever.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.
m (at) mindplay (dot) dk
16.01.2005 9:20
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")+2, date("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($file, 1024*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
drane
8.12.2004 22:53
Somewhere between 4.2.3 and 4.3.9, the behaviour of fread() was changed slightly.

When you ask to fread() 0 bytes of data, it spits out a warning  (IMO for no good reason.  I think reading 0 bytes is perfectly valid, if not very useful.)

Consequently, to write warning-free code using fread, you'd have to take code like this:

$content=fread($fd,filesize($myfile));

and replace it with this:

$content='';
$length=filesize($myfile);
if($length) {
  $content = fread($fd, $length);
}

...or this, depending on your taste:

$length=filesize($myfile);
if($length) {
  $content = fread($fd, $length);
} else {
  $content='';
}

(I'm aware that there are much better ways to read in a whole file at once.  I'm just fixing up someone else's code after a server switch and ran across this stupid warning.)
ibis at connect dot ie
1.12.2004 23:23
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).
mightymrj at hotmail dot com
28.10.2004 19:37
Problem: mime attachments sending as blank or almost completely blank documents (all data is lost)

Explanation: After a couple days of trying to mime pdf attachments without losing all data, I finally came across this function in some obsolete obscure post:

set_magic_quotes_runtime()

This is set to on by default in the machine, and it causes fread() and/or base64_encode() (both used in most mime examples I've seen) to read or encrypt binary without slashes for special characters.  This causes sent files to process incorrectly, breaking, thus truncating most of the data in the file. 

Fix: pass 0 to this function and it will do a one time turn off while your code executes.

example:
<?php
   set_magic_quotes_runtime
(0);
?>

This can also been turned off in the php.ini file, but I'm not sure what uses that setting or what the consequences might be.

info:
   http://us2.php.net/manual/en/function.set-magic-quotes-runtime.php
fpinho at hotpop dot com
13.10.2004 23:21
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:

   while(!feof($file) and (connection_status()==0)) {
     print(fread($file, 1024*1024));
     set_time_limit(0);
     flush();
   }

Frederico Pinho
aidan at php dot net
1.07.2004 13:55
As of PHP 5.0.0 and PHP 4.3.8, fread($stream, 2048) will only grab 1 packet worth of data from the buffer in a TCP/IP or UDP stream.

Note: 2048 is the suggested size to make sure you get all of one packet, any size larger than that will still have the same result
Mark
15.06.2004 2:37
Unfortunately, or maybe fortunately, magic_quotes_runtime setting in php.ini affects this call, even if you specify the bytes count, and even if you specify that the file you're reading is binary (via 'rb' when calling fopen.) So be careful, especially if you're using someone else's library that depends on binary read.
webmaster at wildpeaks dot com
14.05.2004 9:32
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;
}
?>
squeegee
13.04.2004 14:25
fread also works for fsockopen's that are open-ended (no feof) if you know how the last packet for a particular set of data should end. For example, if you sent a command to an nntp server, the reply from the server would end with a dot and a carriage return/linefeed. The connection still stays open for more commands, but doing it this way is more efficient than doing line-by-line fgets until you get to the end of the reply.

<?php
if(($res=nntp_cmd($conn,"BODY $msgid",222))===false){
    continue;
}else{
   
$contents='';
    while(
1){
       
$packet=fread($conn,8192);
       
$contents.=$packet;
        if(
substr($packet,-3)==".\r\n")break;
    }
   
// do something with $contents
}
?>
Brian
17.05.2003 11:10
Two quick notes on download prompting...
First, the following line:

<?php
header
("Cache-Control: no-cache, must-revalidate");
?>

causes IE6 to prompt you to download the script instead of the output and will fail to connect.  Take out that header and everything works perfectly.

Pragma: no-cache doesn't cause a problem.

Second, Mozilla tries to add .php to the download file name if content-type is application. Changing the content type to the more specific MIME type (such as audio/mpeg) fixes that but causes IE to try its plugins (such as Quicktime).

The fix I found for that to specify attachment instead of inline.  Here's my code: a prompted, small buffer MP3 download:

<?php
function downloadMP3 ($fileDir, $fileName) {
  
$completeFilePath=$fileDir.'/'.$fileName;
  
header('Pragma: no-cache');
  
header("Content-type: audio/mpeg\nContent-Disposition: attachment; filename=\"" . $fileName . "\"\nContent-length: ".(string)(filesize($completeFilePath)));
  
$fd=fopen($completeFilePath,'rb');
      while(!
feof($fd)) {
         print(
fread($fd, 4096));
        
flush();
      }
}
?>
c97 at c97 dot art dot pl
20.11.2002 18:02
Simple script to limit browser download speed using fread function.

<?php

$file
= "test.mp3"; // file to be send to the client
$speed = 8.5; // 8,5 kb/s download rate limit

if(file_exists($file) && is_file($file)) {

   
header("Cache-control: private");
   
header("Content-Type: application/octet-stream");
   
header("Content-Length: ".filesize($file));
   
header("Content-Disposition: filename=$file" . "%20");

   
flush();

   
$fd = fopen($file, "r");
    while(!
feof($fd)) {
         echo
fread($fd, round($speed*1024));
       
flush();
       
sleep(1);
    }
   
fclose ($fd);

}

?>
rob at lbox.org
14.11.2002 10:28
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.site.com/img.jpg", "rb");

if(
$fp){
 while(!
feof($fp)) {
    
$img = $img . fread($fp, 1024);
 }
}
?>

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.
mail at scherzbold dot net
8.07.2002 3:09
I wrote a simple function for grabbing binary files from the web.

<?php
function wwwcopy($file,$nfile)
{
   
$fp = @fopen($file,"rb");
    while(!
feof($fp))
    {
       
$cont.= fread($fp,1024);
    }
   
fclose($fp);

   
$fp2 = @fopen($nfile,"w");
   
fwrite($fp2,$cont);
   
fclose($fp2);
}
?>
sbedbergAT at ucdavisDOT dot edu
10.06.2002 17:40
PHP seems to preallocate a buffer of length <length> - so, you may need to increase your memory_limit if you use a large <length>, even though the actual bytecount read is small.
(this is on php 4.1.1/Solaris 8; your mileage may vary).
heikki dot korpela at wapit dot com
26.08.2000 11:22
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);
}
?>



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)