PHP - CURL设置标题时的奇怪行为

时间:2016-09-28 13:51:40

标签: php curl header

我在PHP中编写了一个函数来发送CURL请求。 代码如下。

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;
}

所以我调用了这个函数

$url = API_ENDPOINT.$method.'/';

$response = curl_post($url,$params_to_send,$headers);
echo $response;

其中$ url包含我的API网址,$ params包含参数作为关联数组和$ header,如下所示

$headers = ['Content-Type'=>'application/json'];

我的问题是,内容类型标题是设置。但是当我在curl_post函数中手动设置它时,如

$refined_headers = ['Content-Type: application/json']

它完美无缺。 我的代码有什么问题。

1 个答案:

答案 0 :(得分:0)

修正了问题。问题是 我在标题之前和之后放了两个单引号,这是不需要的

$refined_headers[] = "'".$name.": ".$value."'"; 

我将其更改为以下内容并解决了问题。

$refined_headers[] = $name.": ".$value; 
相关问题