强制下载文件

时间:2009-05-29 13:05:25

标签: php

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

我想知道如何强制下载任何类型的文件,而不强制下载链接到从该网站链接的其他页面。我知道可以使用标题执行此操作,但我不想打破我网站的其余部分。

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

我应该设置

header('Content-Disposition: attachment;)

整个页面?

2 个答案:

答案 0 :(得分:12)

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

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

Content-Disposition还可以有filename参数。

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

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

文件名通过URL传递给该脚本。或者您使用某些Web服务器功能(例如mod_rewrite)强制类型:

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

答案 1 :(得分:6)

风格略有不同,准备好了:)

$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); 
}
相关问题