2016-09-28 99 views
0

我寫了一個函數在PHP發送一個CURL請求。代碼如下。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 URL和$ PARAMS包含的參數作爲關聯數組和$頭如下

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

功能我問題在於,內容類型標題正在設置。但是當我手動設置它在curl_post函數裏面就像

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

它是完美的工作。 我的代碼有什麼問題。

+0

'[ '內容 - 類型'=> '應用/ JSON'];'不等於'[ '內容 - 類型:應用/ JSON']'檢查引用 –

+0

以下各行已經做到這一點。 。 foreach($ headers as $ name => $ value){ $ refined_headers [] =「'」。$ name。「:」。$ value。「'」; } 由於它沒有工作,我把它手動 –

+0

我的意思是說,你是這樣做的:''$ header = ['Content-Type'=>'application/json'];'which不管用。把它改成'$ headers = ['Content-Type:application/json'];' –

回答

0

修復了這個問題。問題是 我把兩個單引號的頭,這是沒有必要

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

我改變了以下和issueis解決之前和之後。

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