简体   繁体   中英

PHP doesn't send Authorization header

This is my code

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

in the server, i read the content type header, it is okay, but when i read the authorisation header, it is null

why? am i passing them wrong? (if i do, how can the content type is being read in the server? )

Update

adding this code

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

let the server receives the Authorization field, but the received value is:

Basic MDo=

it is not correct, I send different value

Update 2

the current code

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

my problem now is that i send blabla,blabla but i receive blabla,blabla:

notice the extra double dot at the end of the received value

I would suggest using:

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

And remove the Authorization header from the array. This way, curl sets up its own auth header which should be fully complaint by most if not all browsers.

However, if the username or more likely the password contains a : character it would break, encoding should be used here.

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

And obviously decoded at the other end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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