Reputation: 309
I got a file that when given a ?ordernummer=123456
fetches the necessary data from DB and generates a PDF file with FPDF that forces a download of the PDF. Works fine. Now i want to call this file from another page so that when a button or link is pressed it downloads the PDF file. Right now I'm using include()
, it works but is not very elegant in my opinion. I've tried using file_get_contents();
but thats not working either. Does anyone have a good solution?
$ordernummer = "204377";
$postdata = http_build_query(
array(
'ordernummer' => $ordernummer
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://url.nl/pdf/generate_pakbon.php', false, $context);
Upvotes: 0
Views: 3994
Reputation: 4371
What you are looking for is "Force Download" in PHP. This is done by setting the headers of your file correctly followed by reading the file in your PHP file.
Forcing a download using PHP:
In case of a PDF file, you'd need these headers:
header("Content-disposition: attachment; filename=pakbon_".intval($_GET['ordernummer']).".pdf");
header("Content-type: application/pdf");
The filename=
part is the filename you are forcing upon the download. So not the existing file.
After setting the headers, you can read the file using:
readfile('http://ledisvet.nl/pdf/generate_pakbon.php?ordernummer='.intval($_GET['ordernummer']);
If you add this to a document all together and call it 'downloadpakbon.php' you can simply link to <a href="downloadpakbon.php?ordernummer=123456">download pakbon</a>
inside your page and the download will be force. Credits go to the example explained here: http://webdesign.about.com/od/php/ht/force_download.htm
FPDF Only method:
There are other ways available as well. FPDF has a method called 'Output' which you are probably using already. There are 4 possible parameters inside this method, one of the is 'D' which stands for forcing the download: http://www.fpdf.org/en/doc/output.htm
One way to do it is to add an extra parameter to generate_pakbon.php like ?download=true and then basing the final output method on this parameter:
if($_GET['download'] === true) {
$pdf->Output('Order123.pdf', 'D');
} else {
$pdf->Output('Order123.pdf', 'I');
}
Upvotes: 4
Reputation: 41
Your link http://ledisvet.nl/pdf/generate_pakbon.php did download in my browser (Chrome). To ensure this isn't a browser-specific behaviour, add the following lines at the beginning of generate_pakbon.php (NB: ensure this is before any other output)
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=pakbon.pdf");
header("Pragma: no-cache");
header("Expires: 0");
I would then move your quoted code into this php file.
Upvotes: 2