0

I am trying to get a file size of remote file "compiler-latest.zip" (googlecode.com) using cURL without actually downloading it, here is my PHP code:

$url = 'http://closure-compiler.googlecode.com/files/compiler-latest.zip';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // optional
curl_setopt($ch, CURLOPT_MAXREDIRS, 10); // optional
curl_setopt($ch, CURLOPT_TIMEOUT, 60); // optional
$result = curl_exec($ch);
$filesize = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($ch);
print 'Filesize: ' . $filesize . '<br><br>';
print_r($result);

But, I get "HTTP/1.1 404 Not Found" status with a file size (1379 bytes) of this error 404 document. So, if I set (CURLOPT_NOBODY, 0) it downloads file and returns its correct file size (currently 3820320 bytes). My question is how to get a correct file size of "compiler-latest.zip" file without downloading it?

IMPORTANT: this code works as expected with any other url outside of googlecode.com.

hakre
  • 193,403
  • 52
  • 435
  • 836
Ken
  • 1,605
  • 3
  • 13
  • 20
  • 2
    have you using a HEAD method to see if anything useful is returned in the headerS? – jldupont Dec 14 '09 at 17:14
  • yes, I grab a HEADER only it usually contains all necessary data, but not in this particular case. – Ken Dec 14 '09 at 17:20

2 Answers2

2

Use get_headers function:

<?php

$headers = get_headers('http://closure-compiler.googlecode.com/files/compiler-latest.zip');

$content_length = -1;

foreach ($headers as $h)
{
    preg_match('/Content-Length: (\d+)/', $h, $m);
    if (isset($m[1]))
    {
        $content_length = (int)$m[1];
        break;
    }
}

echo $content_length;
OlegK
  • 46
  • 1
  • Thanks, my script already uses this function, more easier way: $data = get_headers($url, 1); echo $data['Content-Length']; I am just curious how it can be done with CURL, that's it. – Ken Dec 15 '09 at 05:35
1

And how to get a file size, when content-length missing?

turbod
  • 1,988
  • 2
  • 17
  • 31
  • See here: http://stackoverflow.com/questions/3894653/how-to-get-the-file-size-of-a-remotely-stored-image-php/3894706%25233894706 – Tal Galili Oct 09 '10 at 15:23