我在 HTTP 身份验证中遇到问题。我无法获取此 url 的内容,因为它需要 http 身份验证。
代码:
<?php
$url = "http://www.abcdefg.com/12345/";
$username = 'username';
$password = 'password';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$out = curl_exec($ch);
print "error:" . curl_error($ch) . "<br />";
print "output:" . $out . "<br /><br />";
curl_close($ch);
?>
问题是: 它没有显示真实内容,而是显示“302 Found, The document has moved here.”
我试过“http://username:password@www.abcdefg.com/12345/”,没用。
访问此 url(1) 时,弹出窗口要求输入用户名和密码。但弹出窗口来自另一个 url(2)(sso 身份验证服务器)。如果通过认证。然后它再次返回到 url(1)。这个时候,我就可以访问这个url(1)的内容了。
我使用 firebug 通过直接从浏览器访问 url 获取以下消息:
第一步
URL: GET http://www.abcdefg.com/12345/
Status: 302 Found
Protocol: http
第 2 步
URL: GET https://www.ssoauth.com/obrareq.cgi?wh=xxx wu=xxx wo=xxx rh=http://www.abcdefg.com ru=/12345/
Status: 302 Redirect
Protocol: https
第 3 步
URL: GET http://www.abcdefg.com/obrar.cgi?cookie=xxxxxxxxxxxxxxx
Status: 302 Found
Protocol: http
第四步
URL: GET http://www.abcdefg.com/12345/
Status: 200 OK
Protocol: http
然后显示内容...
这与 cookie 有关吗? 如何使用 php curl 读取内容?
最佳答案
你必须设置:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
这将使 cURL 服从 302 并生成额外的请求。
关于php curl - 使用 http 身份验证访问 url(需要帮助),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10792419/