简体   繁体   中英

PHP: failed to open stream: HTTP request failed

I have the script below and was wondering why I was getting the error:

failed to open stream: HTTP request failed! HTTP/1.1 401 Authorization Required

The base64 encoded value is in the form username:password and is correct. The API documentation gave the example as:

Authorization: Basic
QWxhZGRpbjpvcGVuIHNlc2FtZQ==

For example, if the user agent uses Aladdin as the username and open sesame as the password, then the field is formed as above in the HTTP header

  <?php
    $postData = array(
        'primaryContact' => array('id' => 1),
        'subject' => 'Something not working'
    );

    $context = stream_context_create(array(
        'http' => array(
            'method' => 'POST',
            'header' => "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=\r\nContent-Type: application/json",
            'content' => json_encode($postData)
        )
    ));

    // Send the request
    $response = file_get_contents('http://127.0.0.1/', FALSE, $context);

    // Check for errors
    if($response === FALSE){
        die('Error');
    }

    // Decode the response
    $responseData = json_decode($response, TRUE);

    // Print the date from the response
    echo $responseData;
    ?>

Any ideas?

Tested and your code works. i think its the server. atleast check the server username and password again (your base64 code is correct)

I tested on: iis 7.5 the website has basic auth setup (http 401 Challenge) (on iis that means that i can use my windows server credentials)

add the $http_response_headers to your error line to get more information.

// Check for errors
if($response === FALSE){
    var_dump($http_response_header);
    die('Error');
}

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