简体   繁体   English

获取远程文件大小(不使用 Content-Length 字段)

[英]get remote file size (without using Content-Length field)

I need to get size of remote file without download.我需要在不下载的情况下获取远程文件的大小。 I use this code, but headers from some sites doesn't contain Content-Length: field.我使用此代码,但某些站点的标头不包含Content-Length:字段。 How can I get filesize in that cases?在那种情况下我怎样才能获得文件大小?

$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;

this is result of echo $data;这是 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

If Content-Length header is not present, that means that file size is unknown.如果 Content-Length header 不存在,则意味着文件大小未知。 In your case you have Content-Disposition header, wich means that downloadable file is an attachment to server response (same as email attachment).在您的情况下,您有 Content-Disposition header,这意味着可下载文件是服务器响应的附件(与 email 附件相同)。 So here if you have no Content-Length header you can't get the size.所以这里如果没有 Content-Length header 是拿不到大小的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM