![](/img/trans.png)
[英]Goutte / GuzzleHTTP Get the Content-Length / Size of the response body
[英]get remote file size (without using Content-Length field)
我需要在不下載的情況下獲取遠程文件的大小。 我使用此代碼,但某些站點的標頭不包含Content-Length:字段。 在那種情況下我怎樣才能獲得文件大小?
$ch = curl_init("http://wordpress.org/latest.zip");
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);
curl_close($ch);
$contentLength = 'unknown';
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
$contentLength = (int)$matches[1];
}
echo $contentLength;
這是 echo $data 的結果;
HTTP/1.1 200 OK
Server: nginx
Date: Tue, 10 Apr 2012 11:32:20 GMT
Content-Type: application/zip
Connection: close
Pragma: no-cache
Cache-control: private
Content-Description: File Transfer
Content-Disposition: attachment; filename=wordpress-3.3.1.zip
Content-MD5: d6332c76ec09fdc13db412ca0b024df9
X-nc: EXPIRED luv 139
如果 Content-Length header 不存在,則意味着文件大小未知。 在您的情況下,您有 Content-Disposition header,這意味着可下載文件是服務器響應的附件(與 email 附件相同)。 所以這里如果沒有 Content-Length header 是拿不到大小的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.