我希望用戶下載文件時,他/她點擊'下載此文件'鏈接。如何強制使用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')下載?
'Content-Transfer-Encoding'不是一個HTTP頭。只是說。 – DaSourcerer