【问题标题】:Download a pdf file using PHP with a search form使用带有搜索表单的 PHP 下载 pdf 文件
【发布时间】:2015-02-03 18:05:02
【问题描述】:

我创建了一个搜索表单,用户可以在其中输入图像代码,搜索时它会让用户下载文件。下面是我的代码

<html>
          <head>
            <title>Search  Contacts</title>
          </head>
          <body>

            <h3>Search Client File</h3>
            <form  method="post" action="#"  id="searchform">
              Type the File Code:<br><br>
                  <input  type="text" name="fcode">
            <br>
      <input  type="submit" name="submit" value="Search">
            </form>

<?php
$filecode=$_POST["fcode"];
     if (!empty($filecode))
     {
$file="/var/www/website/$filecode.pdf";
header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
     }
     else
     {
       echo "No Results";
     }

        ?>
    </body>
    </html>

问题是下载的文件无法查看,或者无法查看,我的代码似乎有什么问题?

【问题讨论】:

  • 文件顶部的标记是否也被渲染到输出?如果是这样,没有 PDF 阅读器会理解它。通常响应文件会在 PHP 脚本中单独发生,而不是被额外的标记包围。
  • @David 对不起,“标记”是什么意思
  • “标记”是“HTML”中的“M”。我的意思是,如果响应同时包含 HTML 和 PDF 文件,那么它不是有效的 PDF。
  • @David 你能建议我应该如何纠正这个问题吗?
  • 嗯,首先你要确认这是否真的是错误。这可以通过检查响应在浏览器的调试工具中确认。如果响应包含此页面中的 HTML,那就是问题所在。 (可能还有其他问题,但要诊断它们,您需要纠正这个问题。)我不完全确定这是问题所在,因为它应该在内容已经开始。

标签: php pdf download


【解决方案1】:

尝试更改此标题:

header('Content-Type: application/pdf');

【讨论】:

    【解决方案2】:

    您的代码将永远无法工作。您在每次执行代码时输出 HTML 表单。如果请求下载,则下载内容将附加到该 HTML 页面。 header() 调用也会失败,并显示“标头已发送”。

    如果您将表单提交到同一页面,则需要先获取下载代码:

    <?php
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
       ... download stuff here
       exit(); // critical - don't let the html get output
    }
    
    ... html form here ...
    

    【讨论】:

      【解决方案3】:

      我已经成功了,下面是代码供参考。

      header('Content-Description: File Transfer');
          header('Content-Type: application/octet-stream');
          header('Content-Disposition: attachment; filename='.basename($file));
          header('Content-Transfer-Encoding: binary');
          header('Expires: 0');
          header('Cache-Control: must-revalidate');
          header('Pragma: public');
          header('Content-Length: ' . filesize($file));
          ob_clean();
          ob_end_flush();
          readfile($file);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多