Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

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

I have a problem in HTTP Authentication. I couldn't get the content of this url because it need http auth.

Code:

<?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);

?>

The Problem is: Instead of show the real content, it shows "302 Found, The document has moved here."

I've tried "http://username:password@www.abcdefg.com/12345/", doesn't work.

When accessing this url(1), a popup window ask for username and password. but the popup window is from another url(2)(a sso authentication server). if pass the authentication. then it gets back to url(1) again. at this time, I can access the content of this url(1).

I use firebug get the following message by accessing the url directly from browser:

Step 1

URL: GET http://www.abcdefg.com/12345/
Status: 302 Found
Protocol: http

Step 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

Step 3

URL: GET http://www.abcdefg.com/obrar.cgi?cookie=xxxxxxxxxxxxxxx
Status: 302 Found
Protocol: http

Step 4

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

Then display the content…

Is this something to do with the cookie? How can I use php curl to read the content?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to set:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

This will make cURL obey the 302 and generate an additional request.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...