Problem with force-downloading files with PHP
I have problem with force browser to download a file. I found that kind of solution my problem:
header("Content-type: application/force-download");
header("Content-Disposition: attachment; filename=$name_of_file");
header("Pragma: no-cache");
header("Expires: 0");
readfile($name_of_file);
exit;
But after that I have my file on screen. Even that make this same result:
header('content-type: text/xml开发者_如何学Python');
header('Content-Disposition: attachment;filename="$filename"');
echo "TEST";
exit;
Where could be a problem?
Unfortunately, attachment for the Content-Disposition header field is not supported that good. That’s why the Content-Type header field value is more important:
If [the Content-Disposition] header is used in a response with the application/octet-stream content-type, the implied suggestion is that the user agent should not display the response, but directly enter a `save response as...' dialog.
Although an unknown content type like application/force-download is supposed to be interpreted like application/octet-stream:
It is expected that many other subtypes of "application" will be defined in the future. MIME implementations must at a minimum treat any unrecognized subtypes as being equivalent to "application/octet-stream".
But you should better play it safe and use application/octet-stream explicitly.
<?php
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($name_of_file));
header("Content-disposition: attachment; filename=" . $name_of_file);
readfile($name_of_file);
die();
1) It is your responsibility to make sure that file does exist and is readable
2) It may be worth adding ob_end_clean();
before sending headers (in case you have sent something already)
EDIT: Removed useless ;
as per comments from porneL, thnx
Just use:
header('Content-Disposition: attachment');
and combine that with mod_rewrite
or such to put correct filename in the URL.
If you have Apache, but you're not using mod_rewrite
, that works too;
http://example.com/download_script.php/nice_filename.xml
This causes download_script.php
to be called. Browsers will "see" nice_filename.xml
as the filename and you won't need the very messy and unreliable filename=…
attribute.
精彩评论