PDA

View Full Version : Force download


tony09uk
11-08-2011, 12:31 AM
I have followed a tutorial to force a download using php.
This:

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

if(!file)
{
// File doesn't exist, output error
die('file not found');
}
else
{
// 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
readfile($file);
}
?>

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?

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

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

gentleone
11-08-2011, 10: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));
@readfile($filename);
exit(0);
?>

tony09uk
11-08-2011, 11: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?

tony09uk
11-08-2011, 12:31 PM
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");
to
header("Content-Type: image/jpeg");

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

gentleone
11-08-2011, 01: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

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