2014-06-08 117 views
0

我有一個zip文件,我希望用戶能夠下載。訣竅是我不希望用戶看到什麼網址,我不想將文件下載到我的服務器。從url獲取zip文件(PHP)

所以我想用戶點擊這樣的鏈接:

http://example.com/download/4 

哪些服務器端訪問我的S3桶這個網址:

https://s3.amazonaws.com/my-bucket/uploads/4.zip 

我試着捲曲,使用S3方法,以及我的download($file_id)函數中的各種headers(),但無法使其工作。這一定很容易,對吧?

+1

你似乎討論的Everything仍然會涉及下載文件到您的服務器,據我所知。這個簡單且看似明顯的解決方案是生成並返回一個帶有短暫到期時間的簽名URL,以允許瀏覽器直接從S3直接下載文件。擁有將在幾秒內到期的URL並擁有您的文件副本之間沒有顯着差異,因此如果您對此方法有一些擔憂,請解釋一下。 –

+0

@ Michael-sqlbot好點。 「這個簡單且看似明顯的解決方案是生成並返回一個簽名的URL」。我同意這是明顯的解決方案。您的方法存在的問題是URL的品牌損失,以及使您的存儲桶結構公開。對於一個愛好網站來說,這些並不是那麼重要,但對於一個企業來說,它們可以變成現實。 –

回答

0

感謝@Xatenev的幫助。這實際上是什麼對我來說:

$path = '/my-bucket/uploads/4.zip'; // the file made available for download via this PHP file 
$mm_type="application/zip"; // modify accordingly to the file type of $path, but in most cases no need to do so 

header("Content-Type: " . $mm_type); 
header('Content-Disposition: attachment; filename="'.basename($path).'"'); 
readfile($path); // outputs the content of the file 

exit(); 
+0

哦 - 你有沒有嘗試再次添加其他頭文件?也許這只是mime_type這是不正確的? – Xatenev

2

你的權利,它很容易。也許你會寫這樣的事:

$path = '/my-bucket/uploads/4.zip'; // the file made available for download via this PHP file 
$mm_type="application/x-compressed"; // modify accordingly to the file type of $path, but in most cases no need to do so 

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: " . $mm_type); 
header("Content-Length: " .(string)(filesize($path))); 
header('Content-Disposition: attachment; filename="'.basename($path).'"'); 
header("Content-Transfer-Encoding: binary\n"); 

readfile($path); // outputs the content of the file 

exit(); 

您可以設置不同的標題,讓您的用戶下載.zip。之後,您將文件放入輸出緩衝區中,並出於安全考慮,然後您以exit()結束腳本。這應該適合你!請記住要更改文件的路徑。

+0

這會在解壓縮時產生可怕的「.cpgz」文件。 –