【问题标题】:Download PDF via PHP not working [closed]通过PHP下载PDF不起作用[关闭]
【发布时间】:2015-01-18 19:49:58
【问题描述】:

我有这个代码 sn-p 我在这里找到的:How to make PDF file downloadable in HTML link?

我尝试更改它,因为我的 PDF 文件位于“资源”目录中。

我以为我做对了,但它不起作用。

谁能解释我做错了什么?

<?php
if (isset($_GET["file"]) && !empty($_GET["file"])) {
$file = $_GET["file"];
$path = "/resources/";
$getFile = $path.$file;
if (file_exists($getFile)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Type: application/force-download");
header('Content-Disposition: attachment; filename=' . urlencode(basename($getFile)));
// header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($getFile));
ob_clean();
flush();
readfile($getFile);
exit;
}
}
?>

我添加了 isset 部分,因为没有它,如果没有设置变量,则会引发错误。

这很好,但是当我添加 $path = "/resources/";和 $getFile = $path.$file;它什么也没做(也没有错误)。

编辑:什么不起作用?文件未下载。

测试于:Internet Explorer 和 Google Chrome。

编辑 2:我页面上的链接如下所示:

<a href="?file=kansasHandbook.pdf">Download PDF File</a>

【问题讨论】:

  • 什么是不起作用
  • 文件未下载。在 IE 和 Chrome 中测试。
  • 更新了我的问题。
  • 您确定路径是 /resources/ 并且与您的 Web 根目录无关吗?
  • 非常确定。我所有的 PDF 文件都在 localhost/design/resources

标签: php pdf download


【解决方案1】:

从绝对路径改变路径

$path = "/resources/";

到相对路径:

$path = "./resources/";

或输入完整的绝对路径,可能类似于:

$path = "/var/www/htdocs/design/resources/";

【讨论】:

    【解决方案2】:

    将我自己的问题的答案发布给任何查看的人:

    我发现这个代码 sn-p 可以工作,而我的却不行。

    <?php
    if(isset($_GET['file']))
    {
    $var_1 = $_GET['file'];
    //    $file = $var_1;
    
    $dir = "resources/"; // trailing slash is important
    $file = $dir . $var_1;
    
    if (file_exists($file))
    {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
    }
    } //- the missing closing brace
    ?>
    

    虽然这确实有效,但我仍然很好奇我在代码中做错了什么,以便我可以从中吸取教训。 :)

    这个sn-p来自:How to download a file from specific directory using php header

    【讨论】:

      猜你喜欢
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 2012-01-11
      • 2012-09-22
      相关资源
      最近更新 更多