1
votes

I need to read the size of a file but the server is forcing me to download it first. I note one of the response headers is Content-Type: application/force-download and that seems to bypass my curl inputs...

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch,CURLOPT_TIMEOUT,1000);
curl_exec($ch);
$bytes = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
curl_close($ch);

Any ideas?

2
"Content-Type: application/force-download" has absolutely no meaning to curl and it will simply ignore it. The point of that header is probably to make browsers not recognize it and thus instead of trying to show it inline it would prefer to download it instead. This said, modern browsers will often instead mostly ignore the Content-Type anyway and determine the content by "sniffing" the data instead... As explained in this (outdated) internet-draft: tools.ietf.org/html/draft-abarth-mime-sniff-06Daniel Stenberg

2 Answers

1
votes
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

These two lines reset CURLOPT_NOBODY.

CURLOPT_NOBODY changes method to HEAD and CURLOPT_POST changes it to POST.

Source: http://php.net/manual/en/function.curl-setopt.php

0
votes

Curl conforms with the force-download header, but file_get_contents can be used to limit the file download download to only 1 byte. This solved the problem!

$postdata = http_build_query(
    array(
        'username' => "",
        'password' => ""
    )
);
$params = array(
    'http' => array
    (
      'method' => 'POST',
      'header'=>"Content-type: application/x-www-form-urlencoded\r\n",
      'content' => $postdata
    )
);
$ctx = stream_context_create($params);
file_get_contents($url,false,$ctx,0,1);
$size = str_replace("Content-Length: ","",$http_response_header[4]);