php 用PHP生成下载文件链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1968106/
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
Generate download file link in PHP
提问by Thinker
Possible Duplicate:
open download dialog with php
可能的重复:
用 php 打开下载对话框
I have a link in my page say, <a href='test.pdf'>(Test.pdf)</a>.
When I click on that link, download dialogue box should open to download that file.
Can anyone help me in implementing this in PHP?
我的页面中有一个链接说,<a href='test.pdf'>(Test.pdf)</a>。当我单击该链接时,应打开下载对话框以下载该文件。任何人都可以帮助我在 PHP 中实现它吗?
thanks
谢谢
回答by Jacob Relkin
$filename = 'Test.pdf'; // of course find the exact filename....
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false); // required for certain browsers
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'. basename($filename) . '";');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($filename));
readfile($filename);
exit;
Name the above file as download.php
将上述文件命名为 download.php
HTML:
HTML:
<a href="download.php">Test.pdf</a>
That should do it.
那应该这样做。
回答by Galen
<a href="test.pdf">test.pdf</a>
回答by Erik
In the case of a PDF file, most browsers are going to look for the helper (acrobat) to load it in your browser by default. You are trying to get around this default behavior is my guess.
对于 PDF 文件,默认情况下,大多数浏览器会寻找帮助程序 (acrobat) 将其加载到浏览器中。你试图绕过这个默认行为是我的猜测。
The easiest way to do this (assuming you're on *nix box with apache) is to make an .htaccess file in the directory you want to have this result and add the line:
执行此操作的最简单方法(假设您在使用 apache 的 *nix 框上)是在要获得此结果的目录中创建一个 .htaccess 文件并添加以下行:
AddType application/octet-stream .pdf
AddType 应用程序/八位字节流 .pdf
This will cause any file with the extention .pdf to download by default. You can even have some .pdf files on the page load in the browser while others download by using the FilesMatch directive ( http://www.askapache.com/htaccess/using-filesmatch-and-files-in-htaccess.html).
这将导致默认情况下下载扩展名为 .pdf 的任何文件。您甚至可以在浏览器中加载页面上的一些 .pdf 文件,而使用 FilesMatch 指令下载其他文件 ( http://www.askapache.com/htaccess/using-filesmatch-and-files-in-htaccess.html) .
I realize your original question said "how do I do it with PHP" but I thought I'd post in case you were looking for a simpler, more elegant solution. Do keep in mind any directives you put in an .htaccess file will also affect any sub-directories below it.
我意识到你最初的问题是“我如何用 PHP 做到这一点”,但我想我会发帖以防你正在寻找一个更简单、更优雅的解决方案。请记住,您放在 .htaccess 文件中的任何指令也会影响它下面的任何子目录。

