所以这就是我到目前为止:
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连接。
答案 0 :(得分: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选项手动启用/禁用Basic Auth。
答案 1 :(得分:0)
再次将其设置为空......
curl_setopt(self::$connection, CURLOPT_HTTPAUTH, 0);
这是一个位掩码,0将不设置任何位...
如果这是连续请求,您可能还想重置用户/密码:
curl_setopt(self::$connection, CURLOPT_USERPWD, '');
答案 2 :(得分:0)
正如Baseer所解释的那样,诀窍是你永远不要依赖curl_setopt_array()
,而是始终在CURLOPT_HTTPHEADER
上使用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);
?>