php 强制下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/925854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:20:50  来源:igfitidea点击:

forcing a file to download

php

提问by Joshxtothe4

I have a php page with information, and links to files, such as pdf files. The file types can be anything, as they can be uploaded by a user.

我有一个包含信息的 php 页面和文件链接,例如 pdf 文件。文件类型可以是任何类型,因为它们可以由用户上传。

I would like to know how to force a download for any type of file, without forcing a download of links to other pages linked from the site. I know it's possible to do this with headers, but I don't want to break the rest of my site.

我想知道如何强制下载任何类型的文件,而不强制下载从站点链接的其他页面的链接。我知道可以用标题来做到这一点,但我不想破坏我网站的其余部分。

All the links to other pages are done via Javascript, and the actual link is to #, so maybe this would be OK?

到其他页面的所有链接都是通过 Javascript 完成的,实际链接是到 #,所以也许这样可以?

Should I just set

我应该设置

header('Content-Disposition: attachment;)

for the entire page?

整个页面?

回答by Gumbo

You need to send these two header fields for the particular resources:

您需要为特定资源发送这两个标头字段:

Content-Type: application/octet-stream
Content-Disposition: attachment

The Content-Dispositioncan additionally have a filenameparameter.

Content-Disposition可以另外有一个filename参数。

You can do this either by using a PHP script that sends the files:

您可以使用发送文件的 PHP 脚本来执行此操作:

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment');
readfile($fileToSend);
exit;

And the filenames are passed to that script via URL. Or you use some web server features such as mod_rewriteto force the type:

并且文件名通过 URL 传递给该脚本。或者你使用一些 web 服务器功能,比如mod_rewrite来强制类型:

RewriteEngine on
RewriteRule ^download/ - [L,T=application/octet-stream]

回答by Mantichora

Slightly different style and ready to go :)

风格略有不同,随时可用:)

$file = 'folder/' . $name;

if (! file) {
    die('file not found'); //Or do something 
} else {
    // Set headers
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: binary");
    // Read the file from disk
    readfile($file); 
}