简体   繁体   中英

Force PDF download with PHP - file corrupt on Windows

I have PHP code forcing the download of a PDF. It works on a Mac but not from a Windows machine. I guess it's maybe something to do with the linux server reading the code and creating the file that a mac can read but not 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();

Any suggestions on how to get this PDF download Windows friendly?

The error message is

Could not open 'filename..' because it is either not a supported file type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded).

Maybe your browser is caching an older version of the file. Try adding these headers to your code:

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

Another option:

Save the file in a temporary directory and use the following code to send it to the client:

$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;

It may be that the filename needs .pdf on the end so that Windows can interpret it properly. Try downloading the file renaming it with a .pdf on the end and then trying to open it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM