[英]Retrieve zip from URL, but save with Content-Disposition filename identifier to local file
I'm trying to download a zip from an URL, with something like this: 我正在尝试从URL下载zip文件,如下所示:
$filename = "path/to/File.zip";
file_put_contents($filename, file_get_contents('http://example.com/Download.zip');
My problem is that I want to store that file with the filename from the Content-Disposition header, not the placeholder latest-stable
. 我的问题是我想使用Content-Disposition标头中的文件名而不是占位符latest-stable
存储该文件。 When I predefine the path it keeps that new name. 当我预定义路径时,它将保留该新名称。
If your try to downloading following in your browser: 如果您尝试在浏览器中下载以下内容:
http://downloads.wordpress.org/plugin/jetpack.latest-stable.zip http://downloads.wordpress.org/plugin/jetpack.latest-stable.zip
The download dialog will reveal jetpack.3.1.1.zip
, which is the filename I want, not jetpack.latest-stable.zip
. 下载对话框将显示jetpack.3.1.1.zip
,这是我想要的文件名,而不是jetpack.latest-stable.zip
。
You have the filename already (Download.zip) so you can just: 您已经有了文件名(Download.zip),因此您可以:
$url = 'http://example.com/Download.zip';
$filename = basename($url);
If you have more complex URLs you can use parse_url to get the various URL components. 如果您有更复杂的URL,则可以使用parse_url获取各种URL组件。
From the comments you provided a URL that results in a different filename. 通过注释,您提供了一个URL,该URL导致了不同的文件名。 In that case you can inspect the $http_response_header array, which will be populated with the headers after the call to file_get_contents: 在这种情况下,您可以检查$ 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
)
*/
Look for the Content-Disposition header and strip out the filename (you can use regex and/or http_parse_headers for this). 查找Content-Disposition标头并删除文件名(您可以为此使用regex和/或http_parse_headers )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.