2

[function.fopen]: failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized

I am periodically getting this error, i.e it is only happening at random times, any ideas what would cause this, i have checked my php.ini and allow_url_fopen is set to true.

4 Answers 4

10

If the site requires basic authentication, you can give your credentials this way:

fopen("http://user:[email protected]/path/to/resource", "r");

If it uses digest authentication, you'll have to handle it manually by reading the headers of the failed response and sending a new one with the correct headers. See HTTP context options for how to read and set headers and see how digest works in HTTP authentication with PHP.

You can also use the cURL extension or the HTTP PECL extension.

Sign up to request clarification or add additional context in comments.

Comments

2

10.4.2 401 Unauthorized

The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8). If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user SHOULD be presented the entity that was given in the response, since that entity might include relevant diagnostic information. HTTP access authentication is explained in "HTTP Authentication: Basic and Digest Access Authentication" [43].

Status Code Definitions

Comments

1

You are trying to access a site that requires authentication, as maggie pointed out. fopen() does not support HTTP Basic Authentication, so you must use the Client URL Library to achieve such functionalities.

This has been discussed before.

1 Comment

This is not true. The http wrapper supports basic authentication. What it doesn't support is digest authentication.
1

task - fopen with basic http authentication.

$auth_header = 'Authorization: Basic '.base64_encode("$user:$password");

$f = fopen($url, $open_mode,false, stream_context_create(
    'http'=>array(
        'header' => array($auth_header,$some_other_header,$some_yet_header),
    ),
));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.