2010-09-15 182 views
2

我已經構建了一個簡單的文件管理器,用戶可以下載任何類型的文件,例如pdf,word或gif文件。我希望所有人都下載文件,而不是在瀏覽器中查看它。上傳的文件名存儲在數據庫中。php中的強制文件下載

+3

可能的重複[強制使用PHP下載文件](http://stackoverflow.com/questions/1465573/forcing-to-download-a- file-using-php) – Randolpho 2010-09-15 15:10:52

+0

這個網站已被問及十多次。 – Randolpho 2010-09-15 15:11:16

+0

我要求多格式下載,而不僅僅是pdf。我希望客戶端下載word,excel,gif – ktm 2010-09-15 15:49:09

回答

5

可以使用「內容處置」標題爲:

header("Content-Disposition: attachment"); 

PHP manual提供了用於一個很好的例子。

2

由瀏覽器發送文件強制下載之前通常設置Content-Dispositionattachment

你要麼需要配置Web服務器,爲文件提供此頭或自己通過PHP給他們,像以前一樣發送一個特定的頭:

header('Content-Disposition: attachment; filename=your_file_name.pdf'); 

要注意的是第一個解決方案是爲你贏得更好不會因爲腳本運行時間過長而導致下載量下降(您也可以改變它)。從TCPDF庫採取

6
<?php 
// We'll be outputting a PDF 
header('Content-type: application/pdf'); 

// It will be called downloaded.pdf 
header('Content-Disposition: attachment; filename="downloaded.pdf"'); 

// The PDF source is in original.pdf 
readfile('original.pdf'); 
?> 

http://php.net/manual/en/function.header.php

0
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT\n"); 
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
header("Content-type: application/pdf;\n"); 
$len = filesize($filename); 
header("Content-Length: $len;\n"); 
header("Content-Disposition: attachment; filename=\"downfile.pdf\";\n\n"); 
echo readfile($filename) 
+1

如果你想避免緩存,你最好使用'Cache-Control:no-cache'頭文件。這些換行符('\ n')和';'不是必需的。 – Lekensteyn 2010-09-15 15:40:08

0

源代碼

  // download PDF as file 
      if (ob_get_contents()) { 
       $this->Error('Some data has already been output, can\'t send PDF file'); 
      } 
      header('Content-Description: File Transfer'); 
      if (headers_sent()) { 
       $this->Error('Some data has already been output to browser, can\'t send PDF file'); 
      } 
      header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1 
      header('Pragma: public'); 
      header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past 
      header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); 
      // force download dialog 
      if (strpos(php_sapi_name(), 'cgi') === false) { 
       header('Content-Type: application/force-download'); 
       header('Content-Type: application/octet-stream', false); 
       header('Content-Type: application/download', false); 
       header('Content-Type: application/pdf', false); 
      } else { 
       header('Content-Type: application/pdf'); 
      } 
      // use the Content-Disposition header to supply a recommended filename 
      header('Content-Disposition: attachment; filename="'.basename($name).'";'); 
      header('Content-Transfer-Encoding: binary'); 
      $this->sendOutputData($this->getBuffer(), $this->bufferlen); 
      break; 

反正最重要的部分是

header('Content-Disposition: attachment; filename="'.basename($name).'";'); 

並注意鰭沒有它,它不會工作