Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending file to a browser as attachment

How to send a file to the browser as attachment if the meant file resides on a 3rd party server (without prior downloading or streaming)?

like image 881
12 secs ago Avatar asked Apr 12 '11 20:04

12 secs ago


1 Answers

From another server without downloading to your server:

header('Location: http://thirdparty.com/file.ext');

Without downloading the file locally you have no authorization in the external server, so you have to tell the browser what to do, thus the redirect header, it will tell the server to go directly to the url provided, thus loading the download.

From your server you would do:

if (file_exists($file))
{
    if(false !== ($handler = fopen($file, 'r')))
    {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file)); //Remove

        //Send the content in chunks
        while(false !== ($chunk = fread($handler,4096)))
        {
            echo $chunk;
        }
    }
    exit;
}
echo "<h1>Content error</h1><p>The file does not exist!</p>";

Taken from another question I have answered

like image 198
RobertPitt Avatar answered Sep 17 '22 20:09

RobertPitt