簡體   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