0

I'm asking for a solution how to make PHP download a file without redirect and without reading file source like in this example:

if(1 == 1)
{
    header("Content-Type: application/xml");
    header("Content-Transfer-Encoding: binary");
    header("Cache-Control: private",false); 
    header("Content-Disposition: attachment; filename=example.xml;" );    
    $file = file_get_contents("file.ext");
    echo file;
}

I need solution for download witout file_get_contents make the download like mod_rewrite.

Thanks

Czechnology
  • 14,832
  • 10
  • 62
  • 88
user533178
  • 67
  • 3
  • 11

3 Answers3

3

You could use Apache with the X Send File module https://tn123.org/mod_xsendfile/

mod_xsendfile is a small Apache2 module that processes X-SENDFILE headers registered by the original output handler.

If it encounters the presence of such header it will discard all output and send the file specified by that header instead using Apache internals including all optimizations like caching-headers and sendfile or mmap if configured.

It is useful for processing script-output of e.g. php, perl or any cgi.

Petah
  • 45,477
  • 28
  • 157
  • 213
  • Hello sir, thank's for your answer my question please if I use this module can user know the direct link I need it hidden – user533178 Feb 20 '12 at 04:33
  • @user533178, no you never send the link to the client. You send a header with PHP, and then Apache picks it up and redirects the download automatically. – Petah Feb 20 '12 at 04:37
1
header("Pragma: public"); 
header("Content-Type: application/xml");
header("Cache-Control: private",false);
header("Content-Type: application/force-download"); 
header("Content-Disposition: attachment; filename=file.ext;" );    
readfile("file.ext");
Fredy
  • 2,840
  • 6
  • 29
  • 40
  • Why is `header("Pragma: public");` required? – Umbrella Feb 20 '12 at 12:53
  • You can read here :) [http://stackoverflow.com/questions/1920781/what-does-the-http-header-pragma-public-mean](http://stackoverflow.com/questions/1920781/what-does-the-http-header-pragma-public-mean) – Fredy Feb 22 '12 at 01:52
  • That does not describe a requirement for it. – Umbrella Feb 22 '12 at 03:29
0

You can have PHP send the file straight out the output, instead of into a var with readfile

EDIT

I would recommend instead to read and pass-through the data block at a time, which should perform better because it doesn't have to read the whole file before starting output.

if ($f = fopen($file, 'rb')) {
    while(!feof($f) and (connection_status()==0)) {
        print(fread($f, 1024*8));
        flush();
    }   
    fclose($f);
}   
Umbrella
  • 4,733
  • 2
  • 22
  • 31