简体   繁体   中英

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

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. In your case you have Content-Disposition header, wich means that downloadable file is an attachment to server response (same as email attachment). So here if you have no Content-Length header you can't get the size.

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.

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