PHP不发送Authorization标头

时间:2016-09-05 23:51:27

标签: php http

这是我的代码

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

让服务器收到授权字段,但收到的值是:

  

基本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:

注意接收值末尾的额外双点

1 个答案:

答案 0 :(得分:2)

我建议使用:

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

从数组中删除Authorization标头。 通过这种方式,curl设置了自己的auth标头,如果不是所有浏览器都应该完全投诉。

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

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

显然在另一端解码了。