php curl - access url via browser response: 200 access url via curl response:401?
I have a url which contains all information in the url (username/password/content ect)
If i visit the u开发者_开发百科rl in my browser I get a successful response.
However If I visit the url through curl I get 401.
There is no authentication on the url.
What could be causing this?
Code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://mconnect.co.nz/v1/sendmessage?appname=app&pass=pass&msgclass=test&msgid=6&body=Some+Content&to=02712345678');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $mconnect[$index]['app_name'] . ":" . $mconnect[$index]['app_pass']);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.12 (KHTML, like Gecko) Chrome/9.0.587.0 Safari/534.12');
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_POST, false);
if(curl_exec($ch) === false)
echo 'fail: '.curl_error($ch);
Update...Strange...
So,
I am building my url through $mconnect[$index]['url'] . '?' . http_build_query($url);
which gives me the above url.
So,
If I have
$url = $mconnect[$index]['url'] . '?' . http_build_query($url);
curl_setopt($ch, CURLOPT_URL, $url);
I get the 401.
But,
If I then do
echo $mconnect[$index]['url'] . '?' . http_build_query($url);
I get
http://mconnect.co.nz/v1/sendmessage?appname=app&pass=pass&msgclass=test&msgid=6&body=Some+Content&to=02712345678
so if I then do
$url = 'http://mconnect.co.nz/v1/sendmessage?appname=app&pass=pass&msgclass=test&msgid=6&body=Some+Content&to=02712345678';
curl_setopt($ch, CURLOPT_URL, $url);
Then it works...
any ideas?
The server is likely verifying the user-agent. You probably need to set it to whatever your browser uses.
The parameters you're sending might need to be sent via POST.
$posts = array('pass' => 'password', 'body' => 'lots of content'); // ... etc;
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $posts);
And if this is the case you might not need to use the CURLOPT_USERPWD option.
"There is no authentication on the url." however i see
curl_setopt($ch, CURLOPT_USERPWD, $mconnect[$index]['app_name'] . ":" . $mconnect[$index]['app_pass']);
isnt that for authentication?
Note: You may also try sending the HTTP login details like this
curl_setopt($ch, CURLOPT_URL, 'http://'.$mconnect[$index]['app_name'] . ":" . $mconnect[$index].'@mconnect.co.nz/v........
Try setting the authorization header manually. With something like
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . base64_encode($mconnect[$index]['app_name'] . ":" . $mconnect[$index]['app_pass'])));
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.8
Although not sure why The fix was to build the URL myself instead of using php 5's build_query_string
精彩评论