如何在PHP中自动开始下载?
时间:2020-03-05 18:46:49 来源:igfitidea点击:
我们需要在PHP中添加什么代码,才能在访问链接时自动使浏览器将文件下载到本地计算机?
我专门考虑的功能类似于下载站点,它们会在用户单击软件名称时提示用户将文件保存到磁盘上?
解决方案
回答
这是发送回pdf的示例。
header('Content-type: application/pdf'); header('Content-Disposition: attachment; filename="' . basename($filename) . '"'); header('Content-Transfer-Encoding: binary'); readfile($filename);
@Swish我没有发现应用程序/强制下载内容类型可以做任何不同的事情(在IE和Firefox中进行了测试)。是否有没有不发回实际MIME类型的原因?
同样在PHP手册中,Hayley Watson发表:
If you wish to force a file to be downloaded and saved, instead of being rendered, remember that there is no such MIME type as "application/force-download". The correct type to use in this situation is "application/octet-stream", and using anything else is merely relying on the fact that clients are supposed to ignore unrecognised MIME types and use "application/octet-stream" instead (reference: Sections 4.1.4 and 4.5.1 of RFC 2046).
另外,根据IANA,没有注册的应用程序/强制下载类型。
回答
在输出文件之前发送以下标头:
header("Content-Disposition: attachment; filename=\"" . basename($File) . "\""); header("Content-Type: application/force-download"); header("Content-Length: " . filesize($File)); header("Connection: close");
@grom:对"应用程序/八位字节流" MIME类型很感兴趣。我不知道,一直只使用'application / force-download':)