PHP curl - 使用 HTTP 身份验证访问 URL(需要帮助)


php curl - accessing url with http authentication (need help)

我在HTTP身份验证中遇到问题。我无法获取此网址的内容,因为它需要 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 已找到,文档已移至此处"。

我试过"http://username:password@www.abcdefg.com/12345/",不起作用。

访问此 url(1) 时,弹出窗口会询问用户名和密码。 但弹出窗口来自另一个 URL(2)(SSO 身份验证服务器)。 如果通过身份验证。 然后它再次回到 URL(1)。 这时,我可以访问这个 url(1) 的内容。

我使用Firebug通过直接从浏览器访问URL来获得以下消息:

步骤 1

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

步骤 4

URL: GET http://www.abcdefg.com/12345/
Status: 200 OK
Protocol: http

然后显示内容...

这与饼干有关吗?如何使用 php curl 来读取内容?

您必须设置:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

这将使 cURL 服从 302 并生成额外的请求。