如何在PHP中自动启动下载?

你需要在PHP中添加什么代码来自动让浏览器在访问链接时将文件下载到本地计算机?

我特别想到的function类似于下载网站的function,一旦你点击软件的名称,提示用户将文件保存到磁盘?

在输出文件之前发送以下标题:

header("Content-Disposition: attachment; filename=\"" . basename($File) . "\""); header("Content-Type: application/force-download"); header("Content-Length: " . filesize($File)); header("Connection: close"); 

@grom :有趣的'application / octet- stream'MIMEtypes。 我没有意识到这一点,总是只使用'应用程序/强制下载':)

这是一个发回PDF的例子。

 header('Content-type: application/pdf'); header('Content-Disposition: attachment; filename="' . basename($filename) . '"'); header('Content-Transfer-Encoding: binary'); readfile($filename); 

@Swish我没有find应用程序/强制下载内容types做任何不同的事情(在IE和Firefoxtesting)。 是否有没有发回实际的MIMEtypes的原因?

另外在PHP手册Hayley Watson上发贴:

如果您希望强制下载和保存文件,而不是被渲染,请记住没有像“application / force-download”这样的MIMEtypes。 在这种情况下使用的正确types是“application / octet-stream”,而使用其他任何东西仅仅依赖于客户端应该忽略无法识别的MIMEtypes并使用“application / octet-stream”来代替(参考:Section RFC 2046的4.1.4和4.5.1)。

另外根据IANA ,没有注册申请/强制下载types。

一个干净的例子。

 <?php header('Content-Type: application/download'); header('Content-Disposition: attachment; filename="example.txt"'); header("Content-Length: " . filesize("example.txt")); $fp = fopen("example.txt", "r"); fpassthru($fp); fclose($fp); ?> 

我的代码适用于txt,doc,docx,pdf,ppt,pptx,jpg,png,zip扩展,我认为最好是明确地使用实际的MIMEtypes。

 $file_name = "a.txt"; // extracting the extension: $ext = substr($file_name, strpos($file_name,'.')+1); header('Content-disposition: attachment; filename='.$file_name); if(strtolower($ext) == "txt") { header('Content-type: text/plain'); // works for txt only } else { header('Content-type: application/'.$ext); // works for all extensions except txt } readfile($decrypted_file_path);