Is there a way to get the size of a remote file http://my_url/my_file.txt without downloading the file?
Sure. Make a headers-only request and look for the Content-Length
header.
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
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.