Get remote file size (without using the Content-Length field)

I need to get the size of a deleted file without downloading. I use this code, but the headers from some sites do not contain the Content-Length: field . How can I get the file size in these 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 the 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
+3
source share
1 answer

If the Content-Length header is missing, then the file size is unknown. In your case, you have a Content-Disposition header, which means that the file you upload is an attachment to the server response (just like an email attachment). So, unless you have a Content-Length header, you cannot get the size.

0
source

All Articles