2012-02-20 54 views
0

我要求的解決方案如何使PHP下載文件,而無需重定向並沒有在這個例子中讀取文件源,如:PHP頭文件路徑

if(1 == 1) 
{ 
    header("Content-Type: application/xml"); 
    header("Content-Transfer-Encoding: binary"); 
    header("Cache-Control: private",false); 
    header("Content-Disposition: attachment; filename=example.xml;");  
    $file = file_get_contents("file.ext"); 
    echo file; 
} 

我需要不用其他file_get_contents下載解決方案使下載如mod_rewrite

感謝

+0

'PHP下載文件 - 這是不可能 – zerkms 2012-02-20 04:16:49

+1

@zerkms,沒有它不:mod_xsendfile – Petah 2012-02-20 04:24:40

+0

@Petah:這是非常有趣的,謝謝 – zerkms 2012-02-20 06:34:45

回答

3

你可以使用Apache與X發送文件模塊https://tn123.org/mod_xsendfile/

mod_xsendfile是一個小Apache2的模塊,處理X-SENDFILE由原始輸出處理程序註冊 頭。

如果遇到這種報頭的存在,將丟棄所有 輸出和發送,而不是使用Apache 內部包括像緩存-header和 的sendfile或MMAP所有優化如果配置爲通過該標頭中指定的文件。

它對於處理例如腳本輸出是有用的。 PHP,Perl或任何 CGI。沒有重定向和不讀文件source`

+0

您好先生,感謝您的回答我的問題,如果我使用這個模塊可以用戶知道直接鏈接,我需要它隱藏 – user533178 2012-02-20 04:33:34

+0

@ user533178,沒有你永遠不要發送鏈接到客戶端。你用PHP發送一個頭文件,然後Apache選擇它並自動重定向下載。 – Petah 2012-02-20 04:37:06

+0

感謝您的回答,這是非常好的解決方案 – user533178 2012-02-20 04:40:27

0

你可以讓PHP發送文件直出的輸出,而不是與readfile

編輯

我會建議,而不是一個變種閱讀和直通的數據塊,這應該會更好,因爲它在啓動輸出之前不必讀取整個文件。

if ($f = fopen($file, 'rb')) { 
    while(!feof($f) and (connection_status()==0)) { 
     print(fread($f, 1024*8)); 
     flush(); 
    } 
    fclose($f); 
} 
1
header("Pragma: public"); 
header("Content-Type: application/xml"); 
header("Cache-Control: private",false); 
header("Content-Type: application/force-download"); 
header("Content-Disposition: attachment; filename=file.ext;");  
readfile("file.ext"); 
+0

爲什麼是'標題(「附註:公共「);'需要? – Umbrella 2012-02-20 12:53:08

+0

你可以在這裏閱讀:) [http://stackoverflow.com/questions/1920781/what-does-the-http-header-pragma-public-mean](http://stackoverflow.com/questions/1920781/what -does-the-http-header-pragma-public-mean) – Fredy 2012-02-22 01:52:10

+0

這並沒有描述它的要求。 – Umbrella 2012-02-22 03:29:53