1

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 ?

Community
  • 1
  • 1
confofact
  • 73
  • 1
  • 1
  • 9

4 Answers4

1

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
Jeroen
  • 13,056
  • 4
  • 42
  • 63
1

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

5442224
  • 73
  • 6
  • Once again, the OP already seems to know how to do this, but he'd like to know why he would use it. – Jeroen Jun 07 '12 at 14:56
0

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

Community
  • 1
  • 1
Brad
  • 159,648
  • 54
  • 349
  • 530
  • 2
    It seems to me the OP already knows how to force a download, but he's wondering why he would use it instead of a simple header redirect. – Jeroen Jun 07 '12 at 14:44
  • 1
    Do I not adress that point as well, in the first line of my post? – Brad Jun 07 '12 at 15:19
0

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.

Rick Kuipers
  • 6,616
  • 2
  • 17
  • 37