[英]Opening downloaded zip file creates cpgz file?
如果我為一個zip文件的url創建一個鏈接的href
並單擊該鏈接,我的zip文件會被下載並打開它獲取我期望的內容。
這是HTML:
<a href="http://mysite.com/uploads/my-archive.zip">download zip</a>
問題是我想指向我的應用程序的鏈接,以便我可以確定用戶是否有權訪問此zip文件。
所以我希望我的HTML是這樣的:
<a href="/canDownload">download zip</a>
和我的PHP for /canDownload
頁面:
//business logic to determine if user can download
if($yesCanDownload){
$archive='https://mysite.com/uploads/my-archive.zip';
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=".basename($archive));
header("Content-Length: ".filesize($archive));
ob_clean();
flush();
echo readfile("$archive");
}
所以,我認為問題與header()
代碼有關,但我已經嘗試了一些基於各種谷歌和其他SO建議相關的事情,但沒有工作。
如果你回答我的問題,很可能你也可以回答這個問題: 帶有PHP的壓縮文件在提取后產生cpgz文件
我的答案是在readfile()之前輸出一個空行。
所以我補充說:
ob_end_clean();
ReadFile的($文件名);
但您應該搜索代碼中輸出此行的位置。
readfile的PHP文檔說它將輸出文件的內容並返回一個int。
所以你的代碼, echo readfile("$archive");
,將回顯$archive
(順便說一句,雙引號在這里沒有意義;你應該刪除它們),然后輸出正在返回的int
。 也就是說,你的行應該是: readfile($archive);
此外,您應該使用歸檔的本地路徑(而不是http://鏈接)。
共:
if($yesCanDownload){
$archive='/path/to/my-archive.zip';
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=".basename($archive));
header("Content-Length: ".filesize($archive));
ob_clean();
flush();
readfile($archive);
}
最后,如果這不起作用,請確保filesize($archive)
返回文件的准確長度。
另一個可能的答案,我發現經過多次搜索,我發現*.zip
“解壓”到*.zip.cpgz
的兩個可能原因是:
*.zip
文件已損壞 作為Mac用戶,第二個原因是解壓縮文件的原因:標准Mac OS工具是Archive Utility ,它顯然無法處理> 2GB文件。 (有問題的文件是一個壓縮的4GB raspbian磁盤映像。)
我最終做的是使用我的Mac上已經存在於Virtual Box中的Debian虛擬機。 在Debian 8.2上unzip
6.0解壓縮存檔沒有問題。
您將URL傳遞給readfile()
如:
$archive = 'https://mysite.com/uploads/my-archive.zip';
雖然您應該在服務器上傳遞路徑,例如:
$archive = '/uploads/my-archive.zip';
假設文件位於上傳文件夾中。
另外,請嘗試以下標題:
header("Content-type: application/octet-stream");
header("Content-disposition: attachment; filename=file.zip");
好的,我回答了我自己的問題。
我最初沒有說清楚的主要問題是該文件不在我的應用程序服務器上。 它是在亞馬遜AWS s3桶中。 這就是為什么我在我的問題中使用了一個完整的URL, http://mysite...
而不僅僅是服務器上的文件路徑。 事實證明, fopen()
可以打開網址(所有s3桶“對象”,也就是文件,都有網址),這就是我所做的。
這是我的最終代碼:
$zip= "http://mysite.com/uploads/my-archive.zip"; // my Amazon AWS s3 url
header("Content-Type: archive/zip"); // works with "application/zip" too
header("Content-Disposition: attachment; filename='my-archive.zip"); // what you want to call the downloaded zip file, can be different from what is in the s3 bucket
$zip = fopen($zip,"r"); // open the zip file
echo fpassthru($zip); // deliver the zip file
exit(); //non-essential
在我的情況下,我試圖在public_html上面的目錄中創建文件,並且托管的規則不允許它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.