PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

fscanf> <fputs
Last updated: Fri, 18 Jul 2008

view this page in

fread

(PHP 4, PHP 5)

fread — Legge un file salvaguardando la corrispondenza binaria

Descrizione

string fread ( resource $handle , int $length )

fread() legge fino a length byte dal puntatore al file indicato da handle . La lettura finisce quando sono stati letti length byte o è stata raggiunta EOF, o (nel caso di flussi via rete) quando un pacchetto divnta disponibile, in base a quale evento accada prima.

<?php
// copia il contenuto di un file in una stringa
$filename "/usr/local/something.txt";
$handle fopen($filename"r");
$contents fread($handlefilesize($filename));
fclose($handle);
?>

Avviso

Sui sistemi che differenziano fra file di testo e binari (ad esempio Windows) il file deve essere aperto con il parametro mode di fopen() impostato a 'b'.

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

Avviso

Quando si ricevono dati via rete o pipe, tipo quelli ottenuti leggendo da file remoti o da popen() e fsockopen(), la lettura si fermerà dopo avere ricevuto il pacchetto disponibile. Questo significa che i dati sono ricevuti a blocchi che devono essere raggruppati, come illustrato nell'esempio seguente.

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

Nota: Se si desidera ottenere il contenuto del file in una stringa, utilizzare la funzione file_get_contents() la quale è ancora più performante del codice precedente.

Vedere anche fwrite(), fopen(), fsockopen(), popen(), fgets(), fgetss(), fscanf(), file() e fpassthru().



fscanf> <fputs
Last updated: Fri, 18 Jul 2008
 
add a note add a note User Contributed Notes
fread
hachimuto
26-Sep-2008 02:42
HELLO CODERS.
I'm newbie to php and would like to show you a script that do:
*Download files from server.(implemanted)
*Support resume function.(implemanted)
*Determine the speed of download.(implemanted)
*Link protection(not yet and that's what I want to learn from you if you like.)

I explain the last feature:the server generates a link only "valid for this ip who requested it .the link looks alike something : http://host/downloadit.o-n.php?idx=f7b1424c46ed6705879b2497c6453aaa
                                      &file=yogui-cours-complet-php.zip
the server support resume,so multiple ranges requests,the same ip could download one more time with this link.Now   we need to prevent this from happening  using something like this :
if($range["start"]!=$dbtikt["down_range"]){//IF4446
 //IF THE CLIENT DIDN'T REQUESTED THE CORRECT RANGE.

    exit();
      //WE REFUSE THIS RANGE.

}//IF4446

now some tips ii learned:
=>to allow download of big files you must add code set_time_limit(0);
=>you must proccess the connection abort using ignore_user_abort(true),this means your script will continue executing when the user disconnects from server.
so you could use if(connection_aborted()){do something} to perform finshing tasks.
=>don't put any thing before <?php  code ?>,to avoid header already sent errors,or simply turn on output buffer to prevent php from sending any output until you call flush functions.
=>to provide a limiting speed mechanism,i read always 32*speed bytes from file ,flush it and wait a partical time using usleep(round((1000000*32)/1024)) and its working.
Anonymous
18-Sep-2008 03: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-Jun-2008 08: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;
}

?>
ehy_key1 at hotmail dot de
27-Jun-2008 10:36
This is a rudimentary dummy how to read all data from a stream because i got some problems with stream_get_contents() i decide to write this...

class read_stream
{
    public   $fp;
    private $str;
    private $limit = 8192;
   
    public function read_data()
    {
       $this->str = "";
       $len       = unpack("N",fread($this->fp, 4));
       return $this->rekursiv_($len[1]);
    }
   
    private function rekursiv_($laenge)
    {
        if ($laenge >= $this->limit)
        {
           $this->str .= fread($this->fp, $this->limit);
           $this->rekursiv_($laenge % $this->limit);
        }
        else
        {
         $this->str .= fread($this->fp, $laenge);
        }
        return ($this->str);
    }
}
mail at 3v1n0 dot net
29-Apr-2008 12: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.

<?
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-Apr-2008 03: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
07-Jan-2008 09: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!
phpnet at povaddict dot com dot ar dot invalid
10-Dec-2007 08:14
@kai, Blagovest, and probably others:

Of course fread shouldn't be trusted to read the whole length you requested, that's a basic socket concept. And the manual says so: "Reading stops as soon as a packet becomes available (for network streams)"

In fact I'm having a problem where fread sometimes blocks even though there is *some* data available (it should return as soon as there is 1 byte); *that* shouldn't happen.
matt at matt-darby dot com
10-Oct-2007 07: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
03-Sep-2007 01: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-May-2007 04: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-Mar-2007 07: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-Mar-2007 06: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-Jan-2007 11: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
03-Apr-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
01-Feb-2006 08: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-Jan-2006 11: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-Sep-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-Sep-2005 05: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
01-Jul-2005 06: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-Jun-2005 03: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-Apr-2005 01: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-Apr-2005 08: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
08-Apr-2005 02: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
08-Apr-2005 04: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-Mar-2005 07: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-Mar-2005 09: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
05-Mar-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-Jan-2005 09: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 transfe