2013-12-22 37 views
3

我希望用戶下載文件時,他/她點擊'下載此文件'鏈接。如何強制使用PHP下載文件?

用例:用戶點擊一個鏈接,Web應用程序生成一個文件和「推」它作爲一個下載。

我有以下PHP代碼。雖然文件在服務器中正確生成,但並未下載(並且未顯示下載對話框)。

header("Pragma: public"); 
header("Expires: 0"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("Cache-Control: public"); 
header("Content-Description: File Transfer"); 
header("Content-type: application/octet-stream"); 
header("Content-Disposition: attachment; filename=\"".$filename."\""); 
header("Content-Transfer-Encoding: binary"); 
readfile('file.zip'); 

我嘗試添加以下,但它不工作:

header("Location: file.zip"); // not working 

雖然,我發現了一個JavaScript解決方案(這是工作),嘗試以下重定向:

window.location.href = 'file.zip'; 

問題是,上面的JavaScript做的事情試圖「卸載」當前的窗口/窗體,在這種情況下這對我不起作用。

有沒有解決方案,這只是使用PHP來「強制」文件(在這種情況下'file.zip')下載?

+0

'Content-Transfer-Encoding'不是一個HTTP頭。只是說。 – DaSourcerer

回答

2
$file_url = 'http://www.myremoteserver.com/file.exe'; 
header('Content-Type: application/octet-stream'); 
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
readfile($file_url); // do the double-download-dance (dirty but worky) 

同時一定要添加基於文件的應用程序/ ZIP,應用/ PDF等適當的內容類型 - 但前提是你不想觸發另存爲對話框。

+0

謝謝,但這是行不通的。 – Gandalf

1

我有兩個例子,我使用和工作,以及三個實際上。

HTML

<a href="save_file_1.php">Click here</a> 

PHP(save_file_1.php)

<?php 
$file = 'example.zip'; 

if(!file) 
{ 
    die('file not found'); 
} 
else 
{ 
     header('Content-Description: File Transfer'); 
     header('Content-Type: application/octet-stream'); 
     header('Content-Disposition: attachment; filename='.basename($file)); 
     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($file)); 
     ob_clean(); 
     flush(); 
     readfile($file); 
     exit; 
} 
?> 

而第二個,這是短而甜。

一個對話框會提示用戶保存到...

HTML

<a href="save_file_2.php">Click here</a> 

PHP(save_file_2.php)

<?php 
header('Content-Disposition: attachment; filename=example.zip'); 
readfile("example.zip"); 
?> 

和示例的正上方一個變種:

<?php 
$file = "example.zip"; 
header("Content-Disposition: attachment; filename=$file"); 
readfile("$file"); 
?> 

我已經使用PHP版本5.4.20在託管服務器上測試和工作了所有這些工具(適用於我)。

+0

謝謝,這會創建文件(就像我的示例),但仍會嘗試「卸載」當前表單。這意味着,Chrome或Firefox(或任何瀏覽器)將顯示......「您確定要離開此頁嗎?」警報框。 – Gandalf

+0

不客氣。我需要看看你的表單或HTML,然後(全部/全部代碼),包括可能與你現在/顯示的代碼結合使用的任何其他PHP代碼。 @Gandalf如果你使用的JS也與我/你的代碼一起使用,那麼這可能是錯誤。您目前的代碼使用情況正在導致這種情況。 –

+0

附錄:我也在使用Firefox(最新版本),它沒有生成該消息,所以它顯然與您未顯示的代碼/ HTML有關。 @Gandalf –