繁体   English   中英

如何强制下载存储在服务器上的pdf文件?

[英]How to force a download of a pdf file stored on the server?

我想强制下载存储在服务器上的pdf文件。

到目前为止,我的尝试导致pdf文件损坏。

<div class="w3-row">
  <div class="w3-col l8 s12">
    <div class="w3-card-4 w3-margin w3-white ">
      <div class="w3-display-container">
        <center>
          <header class="w3-teal w3-center">
            <h2><b> You can download you syllabus here </b></h2>
          </header>
          <br>
          <h2 class="w3-container " style="color: darkblue;"><strong><?php echo $branch ?></strong></h2>
          <h3 class="w3-container"><strong><?php echo $sem ?></strong></h3>

          <br>
          <a class="w3-text-red  w3-large" href="script/download.php?filedir='<?php echo "
            script/ ".$dir ?>&filename= <?php echo $name ?>  ' "><strong>Download</strong></a>
          <br>
          <br>
        </center>
      </div>
    </div>
    <hr>
  </div>

下面是download.php

        $path  = $_GET['filedir'] ;
        $filename = $_GET['filename'];


        header('Connection: Keep-Alive');
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        //header('Content-Disposition: attachment; 
        filename="'.basename($filename).'"');
        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($filename));
        ob_clean();
        flush();
        readfile($path);

当您使用basename获取文件名时,您会遇到问题

$path  = $_GET['filedir'] ;
$filename = $_GET['filename'];

header('Connection: Keep-Alive');
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
//header('Content-Disposition: attachment; 
$filename=basename($filename); //change this line;
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($filename));
ob_clean();
flush();
readfile($path);

暂无
暂无

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

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