2014-07-25 299 views
0

我需要創建一個自動啓動下載文件的PHP頁面(我不想公開下載鏈接)。我已經在網上嘗試了幾個例子,但所有的例子最終都會以不正確的內容類型在瀏覽器中打開文件。 例如:無法用PHP強制下載文件

<?php 
// We'll be outputting a ZIP 
header("Content-type: application/zip"); 

// Use Content-Disposition to force a save dialog. 
// The file will be called "downloaded.zip" 
header("Content-Disposition: attachment; filename=downloaded.zip"); 

readfile('downloaded.zip'); 
?> 

當我執行這個頁面,瀏覽器的輸出是: enter image description here 嘗試這個例子中的所有可能的變型後,我的想法是,這個問題是我的託管環境。我應該檢查哪個變量,並可能要求啓用我的提供程序?
謝謝!

+0

嘗試添加更多'header()'。 'header(「Content-Transfer-Encoding:Binary」);'和'header(「Content-Length:」.filesize($ file));' –

+0

哇,我一直在使用PHP很長一段時間,從來沒有聽說過'readfile()'函數。我一直使用'fopen('php:// output','w')'來完成下載。 :)你有沒有嘗試過使用無緩存頭文件? 「Pragma:no-cache」,「Expires:0」也許? – Cypher

+0

你正在使用哪個Web服務器? – Cypher

回答

1

嘗試使用phpinfo()打印出以下變量:SERVER [「HTTP_ACCEPT_ENCODING」]。 我的懷疑是,你沒有zip允許 - 可能是不同的像「gzip」例如。

+0

感謝猜測!用gzip內容類型它的工作! – user2824073

+0

準確地說,這是正確的更改應用:標題(「內容類型:應用程序/ gzip」); – user2824073

0

下面是我在當天使用的代碼:

     header ("Content-Type: application"); 
         header ("Content-Disposition: attachment; filename=\"$file\""); 
         header ("Content-Length: " . filesize ('./FILES/' . $file)); 
         header ("Cache-Control: no-cache"); 
         header ("Pragma: no-cache"); 
         readfile ('./FILES/' . $file); 
只需修改c的內容類型標題即可。

+0

工作與「gzip」內容。謝謝無論如何。 – user2824073