2

I am trying to download a zip file from /tmp folder in Ubuntu. However when I run the Php code it shows garbage text on the browser instead of showing a download box. I tried with a simple text file and instead of showing me a download dialog box it printed its contents on the browser. Why this force-download isn't working. Below is the code.

if (file_exists($dir.$filename)) {
            header("Content-type: application/force-download");
            header("Content-Transfer-Encoding: Binary");
            header("Content-length: ".filesize($dir.$filename));
            header('Content-disposition: attachment; filename='.basename($dir.$filename));
            readfile($dir.$filename);
            exit(0);
        }

    `    
Shehroz
  • 347
  • 2
  • 9
  • 25
  • **Possible solution: http://stackoverflow.com/questions/15123809/force-download-only-displays-in-browser-doesnt-prompt-for-download#answer-22228190** – cssyphus Nov 25 '15 at 05:10

2 Answers2

5

Well, given any browser a MIME type "application/force-download" the browser won't know what to do with it.

Since it is a zip file, the MIME type should be "application/octet-stream" or "application/zip".

if (file_exists($dir . $filename)) {
        header("Content-type: application/zip");
        header("Content-Transfer-Encoding: Binary");
        header("Content-length: " . filesize($dir . $filename));
        header('Content-disposition: attachment; filename=' . basename($dir . $filename));
        readfile($dir . $filename);
        exit(0);
    }
mauris
  • 42,982
  • 15
  • 99
  • 131
0

You cannot read whole file into memory. Change your readfile($_REQUEST['file']); into:

$handle=fopen($_REQUEST['file'], 'rb');
while (!feof($handle))
{
    echo fread($handle, 8192);
    flush();
}
fclose($handle);

This will read 8kb of file, then push it to the client, and so on... It will consume not much memory (as it's not reading whole file at once).

Also when forcing download always use application/octet-stream this will ensure correct sending of binary files.

Seti
  • 2,169
  • 16
  • 26