简体   繁体   English

未使用curl_setopt PHP设置标题

[英]Headers not being set using curl_setopt PHP

I'm using curl_setopt to set the header in my request. 我正在使用curl_setopt在请求中设置标题。 Specifically, I want to make it so the header includes what kind of authorization is being used. 具体来说,我想使其标头包括正在使用的授权类型。

  // 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);

My use case is running tcpdump to analyze the header (by finding the string "Authorization: Basic" and thus getting the base64 encoding of username:password 我的用例正在运行tcpdump来分析标头(通过找到字符串“ Authorization:Basic”,从而获得username:password的base64编码

Thus when this php program sends out this request to $URL (by loading this program's page), TCP Dump should detect the base64 encoding that uis being sent out, right? 因此,当该php程序将该请求发送到$ URL(通过加载该程序的页面)时,TCP Dump应该检测出uis发出的base64编码,对吗?

However, tcpdump doesn't pickup the header and I think it's because I'm not setting the headers correctly. 但是,tcpdump不会提取标头,我认为这是因为我没有正确设置标头。

You need to execute the curl request. 您需要执行curl请求。

$result = curl_exec($ch);

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

If you do not call curl_exec() , you are never sending the request, and therefore never sending the headers. 如果不调用curl_exec() ,则永远不会发送请求,因此curl_exec()不会发送标头。

Looks OK to me. 在我看来还可以。 However, you don't need the Authorization header when using CURLOPT_USERPWD since it will override any existing Authorizations headers. 但是,在使用CURLOPT_USERPWD时,您不需要Authorization标头,因为它将覆盖任何现有的Authorizations标头。 in the headers array. 在headers数组中。

A suggestion is to debug you curl request by sending it to http://requestb.in . 一个建议是通过将curl请求发送到http://requestb.in来调试它。

The way you set HTTP headers is right. 设置HTTP标头的方法是正确的。
Did you forget to call curl_exec($ch); 你忘了打电话给curl_exec($ch); after all that? 毕竟呢?

you have to run curl_exec first: 您必须先运行curl_exec:

$result=curl_exec ($ch);

and then check the status code: 然后检查状态码:

$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