无法下载 PDF 文件

No download of PDF-files possible

我正在尝试将 PDF 文件下载到本地计算机上。 在本地主机的 Xampp 下,出现正常的下载-window。无法使用 Adob​​e 读取下载内容。

zip 下载也是如此。

在我的网站上,这个 window 没有出现,相反,pdf 文件在浏览器选项卡中显示为乱码。

因此 pdf 肯定存在并且可以通过某种方式访问​​和下载。

我找不到代码有什么问题...

请帮忙。


    <?php
      if (isset($_POST["hilfe_de"]))
       {
         $filepath = "dateien/";
         $file = "callershelp_help-de.pdf";
         header('Content-Description: File Transfer');
         header("Content-Type: application/pdf");
         header("Content-Transfer-Encoding: Binary");
         header("Content-Disposition: attachment; filename=".$file);
         header("Content-Length: ". filesize($filepath.$file));
         @readfile($filepath.$file);
       }
    ?>
    
    ... some html-stuff
    
    <form method="post">
      <table>
        <td>
          <tr>
            &nbsp;Callershelp_Hilfe_DE.pdf
          </tr>
        <tr>
          &nbsp;
        </tr>
        <tr>
          <input type="submit" name="hilfe_de" value="Download">
        </tr>
      </td>
     </table
    </form>

我认为问题在于您没有提供完整路径,这就是 @readfile 无法读取 PDF 的原因。您可以为此使用 dirname

   
$filepath = dirname(__FILE__) . '/dateien/'; // equals the path of your script (__FILE__) plus the folder "dateien"
$file = "callershelp_help-de.pdf";

header('Content-Description: File Transfer');
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: Binary");
header('Content-Disposition: attachment; filename="' . $file . '"'); // improvement, see https://www.php.net/manual/en/function.readfile.php#114450
header("Content-Length: ". filesize($filepath . $file));

@readfile($filepath . $file);

来自德国的问候,

约翰内斯

问题已解决: PHP 有时会出现前导空格问题。 为了更好地阅读,我缩进了这些行。只有在删除前两行的前导空格后,一切才能正常工作。这花了我几天时间 8-(

    $filepath = '../path/';
    $file = 'file.pdf';
      header('Content-Description: File Transfer');
      header('Content-Type: application/pdf');
      header('Content-Transfer-Encoding: Binary');
      header('Content-Disposition: attachment; filename="' . $file . '"');
      header('Expires: 0');
      header('Cache-Control: must-revalidate');
      header('Pragma: public');      
      header('Content-Length: '. filesize($filepath.$file));
      readfile($filepath.$file);

难以置信...