繁体   English   中英

从URL检索zip,但使用Content-Disposition文件名标识符保存到本地文件

[英]Retrieve zip from URL, but save with Content-Disposition filename identifier to local file

我正在尝试从URL下载zip文件,如下所示:

$filename = "path/to/File.zip";
file_put_contents($filename, file_get_contents('http://example.com/Download.zip');

我的问题是我想使用Content-Disposition标头中的文件名而不是占位符latest-stable存储该文件。 当我预定义路径时,它将保留该新名称。

如果您尝试在浏览器中下载以下内容:

http://downloads.wordpress.org/plugin/jetpack.latest-stable.zip

下载对话框将显示jetpack.3.1.1.zip ,这是我想要的文件名,而不是jetpack.latest-stable.zip

您已经有了文件名(Download.zip),因此您可以:

$url = 'http://example.com/Download.zip';
$filename = basename($url);

如果您有更复杂的URL,则可以使用parse_url获取各种URL组件。

编辑

通过注释,您提供了一个URL,该URL导致了不同的文件名。 在这种情况下,您可以检查$ http_response_header数组,该数组将在调用file_get_contents之后填充标题:

$data = file_get_contents('http://downloads.wordpress.org/plugin/jetpack.latest-stable.zip');
print_r($http_response_header);
/* output:
Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Server: nginx
    [2] => Date: Thu, 11 Sep 2014 04:11:03 GMT
    [3] => Content-Type: application/zip
    [4] => Content-Length: 7303566
    [5] => Connection: close
    [6] => Cache-control: private
    [7] => Content-Disposition: attachment; filename=jetpack.3.1.1.zip
    [8] => Last-Modified: Wed, 10 Sep 2014 16:17:52 GMT
    [9] => X-Frame-Options: SAMEORIGIN
    [10] => X-nc: EXPIRED lax 202
    [11] => Accept-Ranges: bytes
)
*/

查找Content-Disposition标头并删除文件名(您可以为此使用regex和/或http_parse_headers )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM