打开下载的 zip 文件会创建 cpgz 文件吗?

2022-01-17 00:00:00 http-headers zip zipfile php

如果我将 zip 文件的 url 设为链接的 href 并单击该链接,我的 zip 文件将被下载并打开它会得到我期望的内容.

If I make the url for a zip file the href of a link and click the link, my zip file gets downloaded and opening it gets the contents as I expect.

这是 HTML:

<a href="http://mysite.com/uploads/my-archive.zip">download zip</a>

问题是我希望链接指向我的应用程序,以便我可以确定用户是否有权访问此 zip 文件.

The problem is I'd like the link to point to my application such that I could determine whether the user is authorized to access this zip file.

所以我希望我的 HTML 是这样的:

so I'd like my HTML to be this:

 <a href="/canDownload">download zip</a> 

和我的 /canDownload 页面的 PHP:

and my PHP for the /canDownload page:

//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() 代码有关,但我根据各种 google 和其他 SO 建议尝试了很多与此相关的事情,但都没有工作.

So, I think the problem has to do with the header() code but i've tried a bunch of things related to that based on various google and other SO suggestions and none work.

如果你回答我的问题,你很可能也可以回答这个问题:用 PHP 压缩的文件在解压后生成 cpgz 文件

If you answer my question, it is likely you can answer this question too: Zipped file with PHP results in cpgz file after extraction

推荐答案

好的,我回答了我自己的问题.

Ok, I answered my own question.

我最初并没有说清楚的主要问题是该文件不在我的应用程序服务器上.它位于 Amazon AWS s3 存储桶中.这就是为什么我在我的问题中使用了完整的 url,http://mysite... 而不仅仅是服务器上的文件路径.事实证明 fopen() 可以打开 url(所有 s3 存储桶对象",也就是文件,都有 url),所以这就是我所做的.

The main problem, which I originally didn't make clear, was that the file was not located on my application server. It was in a Amazon AWS s3 bucket. That is why I had used a full url in my question, http://mysite... and not just a file path on the server. As it turns out fopen() can open urls (all s3 bucket "objects", a.k.a. files, have urls) so that is what I did.

这是我的最终代码:

$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

相关文章