title: How to fix Authentication required error 401 when using curl with http authentication
body: <p>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.</p>
  
  <p>When I run my local script, I receive the following error:</p>
  
  <p>"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.</p>
  
  <p>In case you are allowed to request the document, please check your user-id and password and try again.</p>
  
  <p>If you think this is a server error, please contact the webmaster.</p>
  
  <p>Error 401"</p>
  
  <p>I've tried the highest-voted answers from here: <a href="https://stackoverflow.com/questions/2140419/how-do-i-make-a-request-using-http-basic-authentication-with-php-curl">How do I make a request using HTTP basic authentication with PHP curl?</a>
  and I've tried this: <a href="https://thisinterestsme.com/php-curl-http-auth/" rel="nofollow noreferrer">https://thisinterestsme.com/php-curl-http-auth/</a></p>
  
  <p>-> I always receive the same error from above.</p>
  
  <p>I have <code>$username</code> and <code>$password</code> defined. The code I'm using:</p>
  
  <pre><code>$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);
  </code></pre>
  
  <p>After printing the <code>$additionalHeaders</code> variable I get the following additional information before the error:</p>
  
  <p>"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"</p>
  
  <p>Printing <code>$return</code> does not show anything ...</p>