开发者

echo the contents of a File to the user but make it act as a download

I have a script where I get the contents of a file and then echo it to the screen, the problem is that it actually echos the binary file to the page, what I want if for it to act like a d开发者_StackOverflow中文版ownload where the download dialog will display.

how can I achieve this?


From the PHP header() manual:


// We'll be outputting a PDF
header('Content-type: application/pdf');

// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// The PDF source is in original.pdf
readfile('original.pdf');

Change the content-type and the filename. You can user readfile over file_get_contents, but either or should work.


You use the unofficial but ubiquitously supported Content-disposition header. See the first example here. There are a few quirks in browser support for the filename.

You could also simply change the Content-type header to application/octet-stream, but then you can't suggesta a filename to the user without more complex mechanisms.

(Note: application/binary is perhaps an option that's better than application/octet-stream because "If Content-Type matches one of generic values, such as application/octet-stream [...], many browsers treat this as a permission to second-guess the value based on the aforementioned signals, and try to come up with something more specific. The rationale for this step is that some badly configured web servers fall back to these types on all returned content." Source: Google Browser Security Handbook).


You have to change the Content-Type of the HTTP response.

In "raw" PHP (ie. without use of any framework), it would look like:

header("Content-Type: application/octet-stream");

It is necessary to invoke it at the beginning of the script, before any of the data is echoed.


Thanks @Brad for the answer. i have done some modifications in it. What i found is if my content is echoed than no need to do "readfile". What i have done is.

header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="download.pdf"');
$pdf = $thirdPartyAPI->getPdf($ID);
echo $pdf;
ob_clean();
flush();
exit;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜