繁体   English   中英

未使用curl_setopt PHP设置标题

[英]Headers not being set using curl_setopt PHP

我正在使用curl_setopt在请求中设置标题。 具体来说,我想使其标头包括正在使用的授权类型。

  // Define headers to use
  $header = array(
         'HTTP/1.1',
         'Content-type: text/plain',
         'Authorization: Basic ' . base64_encode("$username:$password")
  );

// Below I prepare the request

$ch = curl_init();

 curl_setopt($ch, CURLOPT_URL,$URL);
 curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
 curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);;
 curl_setopt($ch, CURLOPT_HTTPHEADER, $header); // set custom header
 curl_setopt($ch, CURLOPT_HEADER, true);
 curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");

 $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code

 if (curl_errno($ch)) {
     echo 'CURL Error: ' . curl_error($ch);
 }

 $result=curl_exec ($ch);

 echo $result;

 curl_close ($ch);

我的用例正在运行tcpdump来分析标头(通过找到字符串“ Authorization:Basic”,从而获得username:password的base64编码

因此,当该php程序将该请求发送到$ URL(通过加载该程序的页面)时,TCP Dump应该检测出uis发出的base64编码,对吗?

但是,tcpdump不会提取标头,我认为这是因为我没有正确设置标头。

您需要执行curl请求。

$result = curl_exec($ch);

//remember to close the connection too
curl_close($ch).

如果不调用curl_exec() ,则永远不会发送请求,因此curl_exec()不会发送标头。

在我看来还可以。 但是,在使用CURLOPT_USERPWD时,您不需要Authorization标头,因为它将覆盖任何现有的Authorizations标头。 在headers数组中。

一个建议是通过将curl请求发送到http://requestb.in来调试它。

设置HTTP标头的方法是正确的。
你忘了打电话给curl_exec($ch); 毕竟呢?

您必须先运行curl_exec:

$result=curl_exec ($ch);

然后检查状态码:

$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);   //get status code

if (curl_errno($ch)) {
    echo 'CURL Error: ' . curl_error($ch);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM