I'm trying to download a zip from an URL, with something like this:
$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
. 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
The download dialog will reveal jetpack.3.1.1.zip
, which is the filename I want, not jetpack.latest-stable.zip
.
You have the filename already (Download.zip) so you can just:
$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.
From the comments you provided a URL that results in a different filename. 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:
$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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.