Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:[email protected]/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?

like image 536
Strong84 Avatar asked May 29 '12 02:05

Strong84


People also ask

How do I make a request using HTTP basic authentication with PHP cURL?

Yes, Curl has built-in support for basic HTTP server authorization. To make a Curl request with basic authorization credentials, you need to use the following command line parameter: -u username: password (or --user).

How get cURL URL in PHP?

The Way to Download the Contents of a Remote Website to a Local File Using cURL in PHP. $url_name = "https://google.com"; $ch_session = curl_init(); curl_setopt($ch_session, CURLOPT_RETURNTRANSFER, 1);

How do I login to my website using cURL?

For example, if a website has protected content curl allows you to pass authentication credentials. To do so use the following syntax: curl --user "USERNAME:PASSWORD" https://www.domain.com . “USERNAME” must be replaced with your actual username in quotes.


1 Answers

You have to set:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

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

like image 169
ziad-saab Avatar answered Sep 25 '22 02:09

ziad-saab