在标题php curl中发送auth

ven*_*ven 8 php authentication curl header

试图在PHP中做相当于这一点 - 并失败:):

curl -H "X-abc-AUTH: 123456789" http://APIserviceProvider=http://www.cnn.com;
Run Code Online (Sandbox Code Playgroud)

"123456789"是API密钥.命令行语句工作正常.

PHP代码(不起作用):

$urlToGet = "http://www.cnn.com";
$service_url = "http://APIserviceProvider=$urlToGet";

//header

 $contentType = 'text/xml';          //probably not needed
 $method = 'POST';                   //probably not needed
 $auth = 'X-abc-AUTH: 123456789';    //API Key

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $service_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);

//does not work



// curl_setopt($ch, CURLOPT_HTTPHEADER, Array('Content-type: ' . 
   // $contentType . '; auth=' . $auth));

    //works!   (THANKS @Fratyr for the clue):

    curl_setopt($ch, CURLOPT_HTTPHEADER, Array($auth));

//this works too (THANKS @sergiocruz):

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'Some_custom_header: 0',
  'Another_custom_header: 143444,12'
));


//exec

$data = curl_exec($ch);
echo $data;
curl_close($ch);
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

小智 18

为了将自定义标题添加到您的curl中,您应该执行以下操作:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'Some_custom_header: 0',
  'Another_custom_header: 143444,12'
));
Run Code Online (Sandbox Code Playgroud)

因此,以下情况应适用于您的情况(假设X-abc-AUTH是您需要发送的唯一标头):

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'X-abc-AUTH: 123456789' // you can replace this with your $auth variable
));
Run Code Online (Sandbox Code Playgroud)

如果您需要其他自定义标头,您只需在curl_setopt中添加数组即可.

我希望这有帮助 :)