PHP - 使用curl,如何在htpasswd的弹出窗口中发送用户名密码?

时间:2016-07-07 06:07:18

标签: php apache authentication post curl

我必须使用curl提交POST方法,但在打开$ URL时,它有一个提交用户名/密码的弹出窗口(与htpasswd一样)。

由于某种原因,我从服务器获取以下代码

HTTP/1.1 401 Unauthorized and HTTP/1.1 404 Not Foundhttps://www.httpwatch.com/httpgallery/authentication/

// For Debug server response details
$curlOptions = array(
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_FOLLOWLOCATION => TRUE,
    CURLOPT_VERBOSE => TRUE,
    CURLOPT_STDERR => $verbose = fopen('php://temp', 'rw+'),
    CURLOPT_FILETIME => TRUE,
);

// Real meat
$ch = curl_init();
curl_setopt_array($ch, $curlOptions);
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);

// is this the right way here in POST method???
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");// is this correct way to enter username/password in the popup?

$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$result=curl_exec ($ch);

// Pretty print the debug logs
echo '<pre>', 
       !rewind($verbose), 
       stream_get_contents($verbose), 
       "\n", 
     '</pre>';

curl_close ($ch);
echo $result;

如何确保我提交的POST方法确实提交了用户名/密码? (调试日志我不知道我是否已正确提交,服务器也不是由我维护,作为其第三方服务提供商API)

修改

TRY1:失败

// For Debug server response details
$curlOptions = array(
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_FOLLOWLOCATION => TRUE,
    CURLOPT_VERBOSE => TRUE,
    CURLOPT_STDERR => $verbose = fopen('php://temp', 'rw+'),
    CURLOPT_FILETIME => TRUE,
);

// Real meat
$ch = curl_init();
curl_setopt_array($ch, $curlOptions);


//
//
//
//
// STACK-OVERFLOW EXPERT SAID UPDATE THE $URL WITH USER:PASS@ THIS
//
// 
//  
//    

$URL = "http://$username:$password@site.com/postblabla";
curl_setopt($ch, CURLOPT_URL, $URL);



curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);


//
//
//
//
// STACK-OVERFLOW EXPERT SAID REMOVE THIS
//
// 
//  
//    
//curl_setopt($ch, CURLOPT_USERPWD, "$username:$password"); 

$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$result=curl_exec ($ch);

// Pretty print the debug logs
echo '<pre>', 
       !rewind($verbose), 
       stream_get_contents($verbose), 
       "\n", 
     '</pre>';

curl_close ($ch);
echo $result;

1 个答案:

答案 0 :(得分:1)

使用HTTP Auth,您可以发送用户名和密码作为URL的一部分:

<schema>://<username>:<password>@<url>

另见this SO question and answer

但是,CURLOPT_USERPWD应该起作用,因为两种方法都只设置HTTP Authorization标头。 as mentioned here。这也是更安全,因为您的凭据不会在URL中作为纯文本传输,并且可能会使用SSL / TLS,但它们在公开时不会显示出来。

此外,设置HTTP Basic身份验证可能有所帮助。

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);