tags:

views:

75

answers:

3

Is there a way to get the size of a remote file http://my_url/my_file.txt without downloading the file?

+4  A: 

Sure. Make a headers-only request and look for the Content-Length header.

ceejayoz
+7  A: 

Found something about this here:

Here's the best way (that I've found) to get the size of a remote file. Note that HEAD requests don't get the actual body of the request, they just retrieve the headers. So making a HEAD request to a resource that is 100MB will take the same amount of time as a HEAD request to a resource that is 1KB.

<?php
$remoteFile = 'http://us.php.net/get/php-5.2.10.tar.bz2/from/this/mirror';
$ch = curl_init($remoteFile);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //not

necessary unless the file redirects (like the PHP example we're using here) $data = curl_exec($ch); curl_close($ch); if ($data === false) { echo 'cURL failed'; exit; }

$contentLength = 'unknown';
$status = 'unknown';
if (preg_match('/^HTTP\/1\.[01] (\d\d\d)/', $data, $matches)) {
  $status = (int)$matches[1];
}
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
  $contentLength = (int)$matches[1];
}

echo 'HTTP Status: ' . $status . "\n";
echo 'Content-Length: ' . $contentLength;
?>

Result:

HTTP Status: 302 Content-Length: 8808759

NebuSoft
i was reading that earlier, wasn't sure if content-length meant the length or file size
dassouki
well if the request returns a file, the request size *is* the file size
Gareth
But keep in mind that there _can_ be responses without Content-length.
VolkerK
A: 

Since this question is already tagged "php" and "curl", I'm assuming you know how to use Curl in PHP.

If you set curl_setopt(CURLOPT_NOBODY, TRUE) then you will make a HEAD request and can probably check the "Content-Length" header of the response, which will be only headers.

dkamins