iamjonesy
iamjonesy

Reputation: 25122

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).

Upvotes: 0

Views: 3344

Answers (2)

ilanco
ilanco

Reputation: 9957

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;

Upvotes: 1

Jaydee
Jaydee

Reputation: 4158

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.

Upvotes: 0

Related Questions