How do I disable the CURLOPT_HTTPAUTH option in ph

2019-07-30 00:51发布

问题:

So this is what I have so far:

self::$connection = curl_init();
curl_setopt(self::$connection, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt(self::$connection, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt(self::$connection, CURLOPT_URL, $url);

curl_exec(self::$connection); // Do a request that uses Basic Auth
curl_setopt(self::$connection, CURLOPT_HTTPAUTH, false); // <-- Not working as expected - I want to disable Basic Auth here
curl_setopt(self::$connection, CURLOPT_URL, $anotherURL);
curl_exec(self::$connection); // <-- Not working as expected - I want to do a request that does NOT use Basic Auth.

So, if I initialized the CURLOPT_HTTPAUTH option to CURLAUTH_BASIC, how would I go about disabling it?

I need to use the same handle (that is self::$connection) in order to have a persistent HTTP connection.

回答1:

If it helps anyone, this is what I ended up doing:

if ($enableBasicAuth){
    self::$httpHeaders['Authorization'] = 'Basic '.base64_encode("$username:$password");    
}
else if (isset(self::$httpHeaders['Authorization'])){
    unset(self::$httpHeaders['Authorization']);    // Disable Basic Auth
}

// Convert the $httpHeaders array into a format that is used by CURLOPT_HTTPHEADER
$httpHeadersRaw = array();
foreach (self::$httpHeaders as $header=>$value){
    $httpHeadersRaw[] = $header.': '.$value;
}
curl_setopt(self::$connection, CURLOPT_HTTPHEADER, $httpHeadersRaw); // Set the HTTP Basic Auth header manually

Basically I just manually enable/disable Basic Auth using the CURLOPT_HTTPHEADER option.



回答2:

Just set it again to nothing...

curl_setopt(self::$connection, CURLOPT_HTTPAUTH, 0);

This is a bitmask, and 0 would set none of the bits...

If this is a consecutive request, you might also want to reset the user/password:

curl_setopt(self::$connection, CURLOPT_USERPWD, ''); 


回答3:

As Baseer explained, the trick is that you should never rely on curl_setopt_array() but always set the entire array of options directly on CURLOPT_HTTPHEADER with curl_setopt(). If you then want to drop the basic authentication you can simply remove the 'Authorization' line from the headers.

Here is an example that is easy to understand:

<?php
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, 'http://example.com');

// Do a request with basic authentication.
$headers = [
  'Accept: */*',
  'Authorization: Basic ' . base64_encode('username:password'),
];
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
curl_exec($handle);

// Do a subsequent request without basic authentication.
$headers = [
  'Accept: */*',
];
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
curl_exec($handle);
?>


标签: php curl libcurl