【问题标题】:Ignore Content-Type: application/force-download in CURL忽略 Content-Type:CURL 中的应用程序/强制下载
【发布时间】:2023-03-17 10:10:02
【问题描述】:

我需要读取文件的大小,但服务器强制我先下载它。 我注意到其中一个响应标头是 Content-Type: application/force-download ,这似乎绕过了我的 curl 输入...

$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);

有什么想法吗?

【问题讨论】:

  • "Content-Type: application/force-download" 绝对没有 curl 的意义,它只会忽略它。该标头的目的可能是使浏览器无法识别它,因此与其尝试内联显示它,不如下载它。这就是说,现代浏览器通常会忽略 Content-Type,而是通过“嗅探”数据来确定内容......正如这个(过时的)互联网草案中所解释的:tools.ietf.org/html/draft-abarth-mime-sniff-06

标签: php file curl download


【解决方案1】:
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

这两行重置CURLOPT_NOBODY

CURLOPT_NOBODY 将方法更改为 HEAD,CURLOPT_POST 将其更改为 POST。

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

【讨论】:

  • 谢谢,这解释了为什么它不起作用,我在下面发布了解决方法。
【解决方案2】:

Curl 符合 force-download 标头,但 file_get_contents 可用于将文件下载下载限制为仅 1 个字节。这样就解决了问题!

$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]);

【讨论】:

    猜你喜欢
    • 2010-12-05
    • 2017-07-29
    • 2012-05-04
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-01
    相关资源
    最近更新 更多