Search code examples
phpcurlhttp-status-code-401http-authentication

How to fix Authentication required error 401 when using curl with http authentication


I'm using a local php script that runs curl on a script on a remote server. The remote script is protected with http authentication.

When I run my local script, I receive the following error:

"This server could not verify that you are authorized to access the URL "/script.php". You either supplied the wrong credentials (e.g., bad password), or your browser doesn't understand how to supply the credentials required.

In case you are allowed to request the document, please check your user-id and password and try again.

If you think this is a server error, please contact the webmaster.

Error 401"

I've tried the highest-voted answers from here: How do I make a request using HTTP basic authentication with PHP curl? and I've tried this: https://thisinterestsme.com/php-curl-http-auth/

-> I always receive the same error from above.

I have $username and $password defined. The code I'm using:

$url = 'https://' . $page . '/script.php';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml', $additionalHeaders));
print_r($additionalHeaders);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payloadName);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($ch);
print_r($return);
curl_close($ch);

After printing the $additionalHeaders variable I get the following additional information before the error:

"HTTP/1.1 401 Unauthorized Date: Sat, 10 Aug 2019 22:05:26 GMT Server: Apache WWW-Authenticate: Digest realm="Protected", nonce="Xg78fMqPBQA=8d674639fbd19b9ec67b085aa43e90be7a4c57cc", algorithm=MD5, qop="auth" Vary: accept-language,accept-charset Strict-Transport-Security: max-age=16000000 Upgrade: h2 Connection: Upgrade Accept-Ranges: bytes Transfer-Encoding: chunked Content-Type: text/html; charset=utf-8 Content-Language: en"

Printing $return does not show anything ...


Solution

  • your website isn't using HTTP Basic Auth at all, it's using Digest access authentication, google CURLAUTH_DIGEST,

    curl_setopt($ch,CURLOPT_HTTPAUTH,CURLAUTH_DIGEST);