View Full Version : Force download

11-07-2011, 11:31 PM
I have followed a tutorial to force a download using php.

// Define the path to file
$file = 'ryboe_tag_cloud.zip';

// File doesn't exist, output error
die('file not found');
// Set headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: binary");

// Read the file from disk

is the script that was created.

I used a pdf file, which I know works and have no trouble opening.

When I download it and try to open it I get the message "Not supported file type or the file was sent via email and wasn't decoded properley" or words to that effect.

What have I done wrong?

Im working on a localhost (if that makes any difference)

I have looked in the properties of the PDF and there seems to be a difference in the sizes of the files

11-08-2011, 09:09 AM
I had to use this too in the past for a client of mine and I had a lot more PHP headers. Below was actually all that I needed for it to work:

<?php $filename = 'documentname.pdf';
header("Pragma: public");
header("Expires: 0");
header("Pragma: no-cache");
header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-disposition: attachment; filename=' . basename($filename));
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: binary");
header('Content-Length: ' . filesize($filename));

11-08-2011, 10:17 AM
Gentle one you are spot on. It works perfectly :D Thanks.

Now to my next question - in an attempt to learn what is happening - Why wouldn't mine work and why does yours work? Or is this an advanced subject I shouldn't worry about as a beginner?

11-08-2011, 11:31 AM
Ive tried to use it to download a jpg now and when I try to preview the jpg I get nothing. When I try to open it in photoshop it works, what can I do to show it in preview/thumbnails in the windows viewer.

I have changed:
header("Content-Type: application/pdf");
header("Content-Type: image/jpeg");

I had a quick look at php.net but couldn't seem to find anything that I understood

11-08-2011, 12:59 PM
I have no clue about both questions... back then this was soley a copy/paste action of mine... yes, I was guilty... I know :)

Some of the PHP gurus here might help you out with that

11-09-2011, 02:10 AM
http://elouai.com/force-download.php. Yahoogle