【问题标题】:Headers not being set using curl_setopt PHP未使用 curl_setopt PHP 设置标头
【发布时间】:2015-10-27 02:44:11
【问题描述】:

我正在使用 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”,从而获得用户名:密码的 base64 编码

因此当这个 php 程序向 $URL 发送这个请求时(通过加载这个程序的页面),TCP Dump 应该会检测到发送出去的 ui 的 base64 编码,对吧?

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

【问题讨论】:

  • 在 curl_exec() 之前请求 CURLINFO_HTTP_CODE 毫无意义,而且您可能会收到垃圾数据
  • 你能检查一下这段代码返回了什么吗?它可能会给你一些线索! $headers=array();$cookies=array();$debugInfo='';$html=hhb_curl_exec2($ch, $url,$headers,$cookies, $debugInfo);var_dump($headers,$cookies,$调试信息,$html); github.com/divinity76/hhb_.inc.php/blob/master/hhb_.inc.php

标签: php curl tcpdump basic-authentication


【解决方案1】:

你需要执行 curl 请求。

$result = curl_exec($ch);

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

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

【讨论】:

    【解决方案2】:

    我觉得不错。但是,使用 CURLOPT_USERPWD 时不需要 Authorization 标头,因为它会覆盖任何现有的 Authorizations 标头。在 headers 数组中。

    建议通过将 curl 请求发送到 http://requestb.in 来调试您的 curl 请求。

    【讨论】:

      【解决方案3】:

      您设置 HTTP 标头的方式是正确的。
      你忘了打电话给curl_exec($ch);吗?

      【讨论】:

        【解决方案4】:

        你必须先运行 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);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-02-14
          • 2015-11-25
          • 2016-09-26
          • 2016-08-28
          • 2016-04-26
          • 2017-08-19
          • 1970-01-01
          相关资源
          最近更新 更多