【问题标题】:PHP doesn't send Authorization headerPHP不发送授权标头
【发布时间】:2016-09-05 23:51:26
【问题描述】:

这是我的代码

 // create curl resource 
        $ch = curl_init($serviceURL); 

        // set url 
        curl_setopt($ch, CURLOPT_POST, true); 

        // set body
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_data);

        //return the transfer as a string 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 


        $usernamePassword64Encoded = 'username,password';
        $usernamePassword64Encoded = base64_encode ( $usernamePassword64Encoded );

        //make the request content type as json
        $headers = array(
            'Content-type: application/json', 
            'Authorization:Basic '+$usernamePassword64Encoded,
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

在服务器中,我读取了内容类型头,没问题,但是当我读取授权头时,它是null

为什么?我通过他们错了吗? (如果我这样做,如何在服务器中读取内容类型?)

更新

添加此代码

curl_setopt($ch, CURLOPT_USERPWD, "Basic "+$usernamePassword64Encoded);

让服务器接收到Authorization字段,但是接收到的值为:

基本 MDo=

不正确,我发送不同的值

更新 2

当前代码

$ch = curl_init($serviceURL); 

        // set url 
        curl_setopt($ch, CURLOPT_POST, true); 

        // set body
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_data);

        //return the transfer as a string 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 


        $usernamePassword64Encoded = 'blabla,blabla';


        //make the request content type as json
        $headers = array(
            'Content-type: application/json', 
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_USERPWD, $usernamePassword64Encoded);

        // $output contains the output string 
        $output = curl_exec($ch); 

我现在的问题是我发送blabla,blabla 但我收到blabla,blabla:

注意接收到的值末尾多余的双点

【问题讨论】:

  • 某些浏览器处理标题的方式不同。您是否在多个浏览器上尝试过?
  • @JefréN。不,我只用谷歌浏览器尝试过,但我不知道我的客户会使用哪一个,所以我更愿意为所有浏览器解决它,对吧?
  • 您的代码没有问题,可能是因为您阅读的是授权而不是授权?
  • 为什么不使用curl_setopt($ch, CURLOPT_USERPWD, "$login:$password") 而不是构建自己的身份验证标头? Here 是一个简单的例子。
  • MDo= 的翻译消息 = 0: 所以现在它正在接收一些东西。但是,您将用户名和密码编码在同一个字符串中,将它们分开、编码和合并,如下所示:"$encodeduser:$encodedpass" 删除 "Basic" 字符串。

标签: php http


【解决方案1】:

我建议使用:

$usr = 'user';
$pwd = 'pass';
curl_setopt($ch, CURLOPT_USERPWD, "$usr:$pwd");

并从数组中删除 Authorization 标头。 这样,curl 设置了自己的 auth 标头,如果不是所有浏览器,大多数浏览器都应该完全抱怨。

但是,如果用户名或更可能的密码包含: 字符,则会中断,则应在此处使用编码。

$pwd = urlencode( 'my:complex:pass');

显然在另一端解码。

【讨论】:

    猜你喜欢
    • 2020-03-28
    • 1970-01-01
    • 2018-02-04
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 2022-12-24
    • 2017-12-04
    • 1970-01-01
    相关资源
    最近更新 更多