php 我可以使用 CURLOPT_HTTPHEADER 多次调用 curl_setopt 来设置多个标头吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15134575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:38:27  来源:igfitidea点击:

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

phpcurl

提问by hakre

Can I call curl_setoptwith CURLOPT_HTTPHEADERmultiple times to set multiple headers?

我可以打电话curl_setoptCURLOPT_HTTPHEADER多次设置多个标头?

$url = 'http://www.example.com/';

$curlHandle = curl_init($url);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array('Content-type: application/xml'));
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array('Authorization: gfhjui'));

$execResult = curl_exec($curlHandle);

回答by hakre

Following what curl does internally for the request (via the method outlined in this answer to "Php - Debugging Curl") answers the question: No, it is not possible to use the curl_setoptcall with CURLOPT_HTTPHEADER. The second call will overwrite the headers of the first call.

遵循 curl 在内部为请求所做的事情(通过此对“Php - Debugging Curl”的回答中概述的方法)回答了这个问题:不,不能将curl_setopt调用与CURLOPT_HTTPHEADER. 第二个调用将覆盖第一个调用的标头。

Instead the function needs to be called once with all headers:

相反,该函数需要使用所有标头调用一次:

$headers = array(
    'Content-type: application/xml',
    'Authorization: gfhjui',
);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

Related (but different) questions are:

相关(但不同)的问题是:

回答by Pascual Mu?oz

Other type of format :

其他类型的格式:

$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-length: 0';

curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);