强制使用PHP下载PDF文件 - 文件在Windows上损坏


Force PDF download with PHP - file corrupt on Windows

我有PHP代码强制下载PDF。它可以在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友好的任何建议?

错误消息是

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

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

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;

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