[英]PHP - CURL strange behaviour while setting headers
I have written a function in PHP to send a CURl request. 我在PHP中编写了一个函数来发送CURL请求。 The code is given below. 代码如下。
function curl_post($url,$fields,$headers=[],$connect_timeout = 3,$timeout = 20) {
$ch = curl_init();
$postvars = '';
foreach($fields as $key=>$value) {
$postvars .= $key . "=" . $value . "&";
}
$postvars = trim($postvars,'&');
$postvars = json_encode($fields);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1); //0 for a get request
curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,$connect_timeout);
curl_setopt($ch,$timeout, 20);
$refined_headers = [];
if(sizeof($headers)) {
foreach($headers as $name => $value) {
$refined_headers[] = "'".$name.": ".$value."'";
}
print_r($refined_headers);
//$refined_headers = ['Content-Type: application/json'];
//echo $refined_headers;exit;
curl_setopt($ch,CURLOPT_HTTPHEADER,$refined_headers);
}
$response = curl_exec($ch);
$info = curl_getinfo($ch,CURLINFO_CONTENT_TYPE);
print_r($info);
curl_close ($ch);
return $response;
}
So I called the function like this 所以我这样调用了这个函数
$url = API_ENDPOINT.$method.'/';
$response = curl_post($url,$params_to_send,$headers);
echo $response;
where $url contains my API url and $params contain the parameters as associative array and $headers as follows 其中$ url包含我的API url,$ params包含参数作为关联数组和$ headers,如下所示
$headers = ['Content-Type'=>'application/json'];
My problem is that, the content type header is setting. 我的问题是,内容类型标题是设置。 But when I manually set it inside the curl_post function like 但是当我在curl_post函数中手动设置它时
$refined_headers = ['Content-Type: application/json']
it is working perfectly. 它工作得很好。 What is the problem with my code. 我的代码有什么问题。
Fixed the issue. 修复了这个问题。 The problem was I put two single quotes before and after the header, which was not needed 问题是我在标题之前和之后放了两个单引号,这是不需要的
$refined_headers[] = "'".$name.": ".$value."'";
I changed that to the following and the issueis resolved. 我将其更改为以下内容并解决了问题。
$refined_headers[] = $name.": ".$value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.