1

所以这就是我到目前为止所拥有的:

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.

那么,如果我将 CURLOPT_HTTPAUTH 选项初始化为 CURLAUTH_BASIC,我将如何禁用它?

我需要使用相同的句柄(即 self::$connection)以获得持久的 HTTP 连接。

4

3 回答 3

2

如果它对任何人有帮助,这就是我最终要做的事情:

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

基本上我只是使用 CURLOPT_HTTPHEADER 选项手动启用/禁用基本身份验证。

于 2012-06-24T01:07:29.667 回答
0

重新设置为无...

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

这是一个位掩码,0 不会设置任何位...

如果这是一个连续的请求,您可能还想重置用户/密码:

curl_setopt(self::$connection, CURLOPT_USERPWD, ''); 
于 2012-06-23T23:06:18.577 回答
0

正如 Baseer 解释的那样,诀窍是您永远不应该依赖,curl_setopt_array()而是始终将整个选项数组直接设置在CURLOPT_HTTPHEADERwith上curl_setopt()。如果您想放弃基本身份验证,您可以简单地从标题中删除“授权”行。

这是一个易于理解的示例:

<?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);
?>
于 2015-04-16T18:14:45.053 回答