2010-05-07 72 views
1

第一個PHP項目和我卡住了!
我希望允許用戶點擊按鈕或鏈接並下載文件。但是,我的PHP必須先執行一些任務,選擇正確的文件,在db等中記錄下載事件。這個我可以做,但是我該如何發送文件作爲用戶點擊的響應?使用PHP提供文件下載

感謝您的任何幫助。

回答

0

發送適當的頭在你的腳本:

header("content-type: application/pdf"); 

使用正確的mime-type按你的文件和內容發送到使用readfile瀏覽器。

+0

...併發送文件內容到瀏覽器(例如,使用['readfile'(http://fi2.php.net/readfile)) – 2010-05-07 09:28:18

+0

@nikc:是啊,這是正確的。 – Sarfraz 2010-05-07 09:29:43

0

header("Content-type: image/png");(或不管它是什麼),然後你只是輸出文件。

+0

這不會調用下載對話框... – 2010-05-07 09:30:04

2

正如@Sarfraz所示,在完成所需的任務之後,您可以將Content-Type標題發送到瀏覽器,然後將文件內容發送到瀏覽器。然後,瀏覽器將根據用戶設置執行操作,一般情況下,該瀏覽器可以是a)打開並顯示文件,或b)將文件保存到磁盤。

如果要強制將文件保存到磁盤而不是顯示在瀏覽器中,常用的方法是指定MIME類型Content-Type: application/octet-stream。也可以指定一個附件文件名,標題爲。

0

這是一個可以用來直接發送文件到瀏覽器的功能。

$fileName:需要被髮送到瀏覽器 $downloadName路徑+文件的名稱:這是名稱(沒有路徑需要)用戶可以看到在它的下載文件中(不necessarly一樣$filename

function sendFileDirectlyToBrowser($downloadName, $fileName) { 
     if (! file_exists($fileName)) { 
      throw new Exception('file does not exist!'); 
     } 

     $pathInfo = pathinfo($fileName); 

     //list with mime-types http://en.wikipedia.org/wiki/Mime_type#List_of_common_media_types 

     switch (strtolower($pathInfo['extension'])) { 
      case 'csv': 
       header("Content-type: test/csv"); 
       break; 
      case 'doc': 
      case 'docx': 
       header("Content-type: application/msword"); 
       break; 
      case 'gif': 
       header("Content-type: image/gif"); 
       break; 
      case 'jpg': 
      case 'jpeg': 
       header("Content-type: image/jpeg"); 
       break; 
      case 'png': 
       header("Content-type: image/png"); 
       break; 
      case 'pdf': 
       header("Content-type: application/pdf"); 
       break; 
      case 'tiff': 
       header("Content-type: image/tiff"); 
       break; 
      case 'txt': 
       header("Content-type: text/plain"); 
       break; 
      case 'zip': 
       header("Content-type: application/zip"); 
       break; 
      case 'xls': 
      case 'xlsx': 
       if(!(strpos($HTTP_USER_AGENT,'MSIE') === false)) { 
        header("Content-type:application/x-msdownload"); 
       } 
       else { 
        header("Content-type:application/vnd.ms-excel "); 
       } 
       break; 
     } 


     header('Content-Disposition:attachment;filename="' . $downloadName . '"'); 
     print file_get_contents($fileName); 
    }