0

我得到了一个文件,当给定一个文件时,它?ordernummer=123456会从 DB 中获取必要的数据,并使用 FPDF 生成一个 PDF 文件,该文件会强制下载 PDF。工作正常。现在我想从另一个页面调用这个文件,以便在按下按钮或链接时下载 PDF 文件。现在我正在使用include(),它可以工作,但在我看来不是很优雅。我试过使用file_get_contents();,但那也不起作用。有没有人有好的解决方案?

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

2 回答 2

4

您正在寻找的是 PHP 中的“强制下载”。这是通过正确设置文件的标题然后读取 PHP 文件中的文件来完成的。

使用 PHP 强制下载:

如果是 PDF 文件,您需要这些标题:

header("Content-disposition: attachment; filename=pakbon_".intval($_GET['ordernummer']).".pdf");
header("Content-type: application/pdf");

filename=部分是您在下载时强制使用的文件名。所以不是现有文件。

设置标题后,您可以使用以下方法读取文件:

readfile('http://ledisvet.nl/pdf/generate_pakbon.php?ordernummer='.intval($_GET['ordernummer']);

如果你把它添加到一个文档中并称之为“downloadpakbon.php”,你可以简单地链接到<a href="downloadpakbon.php?ordernummer=123456">download pakbon</a>你的页面内部,下载将被强制执行。学分转到此处解释的示例:http ://webdesign.about.com/od/php/ht/force_download.htm

仅 FPDF 方法:

还有其他可用的方法。FPDF 有一个您可能已经在使用的名为“输出”的方法。此方法中有 4 个可能的参数,其中一个是“D”,代表强制下载:http ://www.fpdf.org/en/doc/output.htm

一种方法是在 generate_pakbon.php 中添加一个额外的参数,例如 ?download=true,然后基于此参数的最终输出方法:

if($_GET['download'] === true) {
  $pdf->Output('Order123.pdf', 'D');
} else {
  $pdf->Output('Order123.pdf', 'I');
}
于 2013-10-11T13:39:58.670 回答
2

您的链接http://ledisvet.nl/pdf/generate_pakbon.php确实在我的浏览器(Chrome)中下载。为确保这不是特定于浏览器的行为,请在 generate_pakbon.php 的开头添加以下行(注意:确保这在任何其他输出之前)

header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=pakbon.pdf");
header("Pragma: no-cache");
header("Expires: 0");

然后我会将您引用的代码移动到这个 php 文件中。

于 2013-10-11T13:47:25.950 回答