user533178
user533178

Reputation: 77

php header file path

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

Upvotes: 0

Views: 1951

Answers (3)

Fredy
Fredy

Reputation: 2910

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");

Upvotes: 1

Umbrella
Umbrella

Reputation: 4788

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);
}   

Upvotes: 0

Petah
Petah

Reputation: 46050

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.

Upvotes: 3

Related Questions