1
votes

Possible Duplicate:
Forcing to download a file using PHP

When we need to force user to download a file, we use header with several parameters/options. What if I use

header("location:test.xlsx");

This is working :) Is there any drawback of using this shortcut ?

4

4 Answers

1
votes

This approach should solve the problems mentioned here

download.php?filename=test.xlsx

if isset ($_GET['filename']){
$filename = $_GET['filename']
}
else{
die();
}

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');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);

And of course don't forget to secure this so users can't download other files

1
votes

There are a few disadvantages to this method:

  1. If the file is one the browser can read, it won't be downloaded (like .txt, .pdf, .html, .jpg, .png, .gif and more), but simply be shown within the browser

  2. Users get the direct link to the file. Quite often, you don't want this because they can give this link to others, so...

    1. it will cost you more bandwidth
    2. it can't be used for private files
    3. if it's an image, they can hotlink to it
0
votes

All you're doing is redirecting to a file. This is no different than if they went to it directly.

If you are trying to force a download, you need to set your Content-Disposition header appropriately.

header('Content-Disposition: attachment');

Note that you can't use this header when redirecting... this header must be sent with the file contents. See also: https://stackoverflow.com/a/3719029/362536

0
votes

Not every file is forced to download.

If you were to use that header() on a .jpg the browser won't open the download dialog but will just show the image.