我正试图从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
。
您已经有了文件名(下载.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)。