【问题标题】:Force PDF download with PHP - file corrupt on Windows使用 PHP 强制下载 PDF - Windows 上的文件损坏
【发布时间】:2012-05-21 09:45:06
【问题描述】:

我有强制下载 PDF 的 PHP 代码。它适用于 Mac,但不适用于 Windows 机器。我想这可能与linux服务器读取代码并创建mac可以读取但windows不能读取的文件有关?

$filename = str_replace(' ', '%20', $_GET['brochure']);
header('Cache-Control: public');
header('Content-type: application/pdf');
header("Content-disposition: attachment; filename=\"$filename\"");
readfile('http://siteurl.com/media/download/'.$filename);
die();

关于如何让这个 PDF 下载 Windows 友好的任何建议?

错误信息是

无法打开“文件名..”,因为它不是受支持的文件 类型或因为文件已损坏(例如,它是作为 电子邮件附件且未正确解码)。

【问题讨论】:

  • 如果您将浏览器直接指向http://siteurl.com/media/download/'.$filename会怎样?
  • 尝试保存文件并在记事本(或类似的简单文件编辑器)中打开它,看看文件顶部是否有任何错误。
  • @ilanco 是的,没问题。但是下载器(客户端请求)不能看到该网址
  • @BartS。打开文件,它实际上包含上面代码链接所在的呈现的 html 页面
  • 这意味着您没有读取正确的文件。你确定你正确使用readfile() 吗?它不应该指向本地文件系统上的 PDF(类似于readfile('/var/www/files/media/' . $filename):?现在您正在从另一个虚拟主机读取文件。

标签: php pdf header


【解决方案1】:

也许您的浏览器正在缓存文件的旧版本。尝试将这些标头添加到您的代码中:

header("Cache-Control:  maxage=1");
header("Pragma: public");

另一种选择:

将文件保存在临时目录中,并使用以下代码将其发送给客户端:

$file = readfile('/tmp/'.$filename);
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;

【讨论】:

  • 谢谢,但仍然收到错误消息 - 我已将其添加到我的问题中
【解决方案2】:

文件名可能需要 .pdf 结尾,以便 Windows 可以正确解释它。尝试下载文件并在末尾重命名为 .pdf,然后尝试打开它。

【讨论】:

  • 查看 Windows 中的属性,“文件类型”设置为 Adob​​e Acrobat Document (.pdf)
  • "无法打开 'filename..'" & "打开了文件,它实际上包含渲染的 html 页面"。对我来说,下载文件的链接似乎有问题。您可以在链接展开后发布链接的实际文本吗?
猜你喜欢
  • 1970-01-01
  • 2013-03-31
  • 2012-12-05
  • 1970-01-01
  • 2013-07-12
  • 1970-01-01
  • 2015-10-12
  • 1970-01-01
相关资源
最近更新 更多