Linux – retrieve file size from HTTP headers without downloading the file with CURL (no HEAD)

curlhttphttp-headerslinux

What i want to do is knowa file size and not download it.
I've tried it with HEAD but the server doesn't respond
curl_setopt($curl, CURLOPT_NOBODY, true);
if i quit this , it will , but it will download the whole file…

So if i could somehow tell curl that the max received data should not pass certain bytes and stop, or give a timeout, to not wait until the whole file is downloaded ,

In a normal download :

GET /filepath HTTP/1.1
Host: host.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive

response header

HTTP/1.0 200 OK
Server: Apache/ (Debian GNU/Linux) PHP/
Content-Type: application/octet-stream
ETag: "MFFPJ28A"
Content-Length: 3342417
Content-Disposition: attachment
Cache-Control: private
Content-Transfer-Encoding: binary
Accept-Ranges: bytes

FILE_CONTENTS_FOLLOWING

I tried to specify ranges from 0 to 100 for example
but then i get Content-Length: 101
so no use there…

Best Answer

Find out why your server does not respond to the HEAD request. This is exactly the purpose of the HEAD request :-)

Another option would be to start fetching the file and then just kill the connection.

Are you calling curl from PHP? In the callback function you could receive the header and then stop.

You can define such a callback with curl_setopt, option CURLOPT_HEADERFUNCTION.

Try using curl_close within this function to stop the transfer. But I did not test this.