简体   繁体   English

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

[英]Download a pdf file using PHP with a search form

I've created a search form where the user would input the image code and when searched it will let the user download the file. 我创建了一个搜索表单,用户可以在其中输入图像代码,并且在搜索时可以让用户下载文件。 Below is my code 下面是我的代码

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

The problem is that the downloaded file is unable to be viewed, or unviewable, what seems to be the problem with my code? 问题是下载的文件无法查看或无法查看,我的代码似乎是什么问题?

尝试更改此标头:

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

Your code will never work. 您的代码将永远无法工作。 You are outputting your HTML form at the start of every execution of the code. 您将在每次执行代码时开始输出HTML表单。 If a download was requested, the download will be appended to that HTML page. 如果请求下载,下载将被附加到该HTML页面。 And the header() calls will fail as well with "headers already sent". 并且header()调用也将因“ headers has sent”而失败。

If you're submitting your form to the same page, you need to have your download code FIRST: 如果您要将表单提交到同一页面,则需要先下载代码:

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

... html form here ...

I've made it to work, below is the code for reference. 我已经使其正常工作,下面是供参考的代码。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM