使用PHP和搜索表单下载pdf文件

使用PHP和搜索表单下载pdf文件,php,pdf,download,Php,Pdf,Download,我已经创建了一个搜索表单,用户可以在其中输入图像代码,搜索时可以让用户下载文件。下面是我的代码 <html> <head> <title>Search Contacts</title> </head> <body> <h3>Search Client File</h3>

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

<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>

搜索联系人
搜索客户端文件
键入文件代码:



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

尝试更改此标题:

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

你的代码永远不会工作。在每次执行代码时,您都会输出HTML表单。如果请求下载,下载将附加到该HTML页面。而
header()
调用也将失败,“headers ready sent”

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

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

... html form here ...

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

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

文件顶部的标记是否也呈现到输出中?如果是这样,没有一个PDF阅读器会理解它。通常,用文件响应会在PHP脚本中单独发生,而不会被其他标记包围。@David抱歉,但是“标记”是什么意思“标记”是“HTML”中的“M”。我的意思是,如果响应同时包含HTML和PDF文件,则它不是有效的PDF。@David,您能建议我如何更正此错误吗?首先,您需要确认这是否是错误。通过检查响应,可以在浏览器的调试工具中确认这一点。如果响应包含此页面中的HTML,那么这就是问题所在。(可能还有其他问题,但要诊断这些问题,您需要更正此问题。)我不完全确定这是问题所在,因为在内容已经开始之后,它会给您一个关于修改标题的错误。