How to set cookie in PHP cURL request - php

I'm trying to establish a connection with a real-estate listings API in Canada (CREA), and according to the documentation:
A successful Login response header includes a Set-Cookie with
X-SESSIONID value. This X-SessionID value needs to be submitted with
every request after logging in.
The service provides a sample API for setting everything up, but whenever I attempt to grab the X-SESSIONID value and set it for a subsequent request, it doesn't seem to work, and I get a 401 Unauthorized header on all subsequent requests (even though I am able to successfully grab the X-SessionID info).
Here is the code that I am using now:
<?php
$ch = curl_init('http://sample.data.crea.ca/Login.svc/Login');
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, 'CXLHfDVrziCfvwgCuL8nUahC:mFqMsCSPdnb5WO1gpEEtDCHH');
$xml = curl_exec($ch);
curl_close($ch);
echo '<pre>' . htmlspecialchars($xml) . '</pre>';
preg_match('|Set-Cookie: (X-SESSIONID=.*?);.*|', $xml, $match);
echo '<pre>';
print_r($match);
echo '</pre>';
$ch = curl_init('http://sample.data.crea.ca/Metadata.svc/GetMetadata?Type=METADATA-RESOURCE&Format=STANDARD-XML&ID=0');
curl_setopt($ch, CURLOPT_COOKIE, $match[1]);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xml = curl_exec($ch);
curl_close($ch);
echo '<pre>' . htmlspecialchars($xml) . '</pre>';
Because this is a sample API available to anyone for free, you can run the code above as is to see the error I am getting.
Any advice on how to properly submit the X-SessionID value so that I can be properly authenticated and make subsequent requests would be greatly appreciated.
Thank you.

Just do:
curl_setopt($ch, CURLOPT_COOKIEJAR, '');
Now curl will take care of the cookies. You don't need to parse anything or set them manually

Related

php curl function not giving the required result

I need help with API Integration. When I echo the variable $url, I get the result, but I do not know why cURL is not working for me:
<?php
$token="43e6c623dda8f35df4bXXXfa5f0ec57d58e91154a ";
$format="json";
$waybill="974510010010";
$ref_nos="";//either this or waybill
$verbose="0";// meta info need to append in url
$url="https://test.delhivery.com/api/packages/json/?token=".$token."&format=".$format."&waybill=".$waybill."&ref_nos=".$ref_nos."&verbose=".$verbose;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
echo curl_error($ch);
$return = curl_exec ($ch);
curl_close ($ch);
echo $return;
?>
Do you have access to the service you are connecting to?
It could be that the service requires the data as POST variables as opposed to the GET parameters you are sending.
Or perhaps some error handling on server that does not validate the waybill value you are sending. The ref_nos variable is also empty, which some applications could interpret as invalid. A tips would be to omit the ref_nos variable from the request string if its value is empty.

Accessing Actiontec modem screens via PHP

I have an Actiontec V1000H router. I want to access its "WAN Ethernet Status" page using a script (which will extract the sent and received packet counts for plotting). From a browser, this URL works fine:
http://192.168.1.1/modemstatus_wanethstatus.html
But, when I use that URL in my script, I nearly always get the main screen. (It works on rare occasions.) Here's my script:
$wanStatusUrl = "http://192.168.1.1/modemstatus_wanethstatus.html";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $wanStatusUrl);
curl_setopt($ch, CURLOPT_USERPWD, 'admin:myPassword');
$output = curl_exec($ch);
curl_close($ch);
I need help accessing the modemstatus_wanethstatus.html page. I believe the issue is due to some idiocycracy of the modem.
Use this so that curl return you the html source as response into your $output:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
The main screen has a "login" button, and adding the equivalent of that prior to accessing the WAN Status screen made it work. So, for the record:
// login
$loginUrl = 'http://192.168.1.1/login.cgi?inputUserName=admin&inputPassword=myPassword&nothankyou=1';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $loginUrl);
curl_exec($ch);
curl_close($ch);
// get status page
$wanStatusUrl = "http://192.168.1.1/modemstatus_wanethstatus.html";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $wanStatusUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // so curl_exec returns the response
$responseText = curl_exec($ch);
curl_close($ch);
// print $responseText; // contains wanEthStatus_ReceivedPackets and wanEthStatus_SendPackets
// get the two packet counts ... wanEthStatus_ReceivedPackets and wanEthStatus_SendPackets
preg_match( "/wanEthStatus_ReceivedPackets.*?\'(\d+)\';.*?\'(\d+)\';.*?wanEthStatus_TimeSpan/s", $responseText, $matches );
print_r( $matches );
"Man Always Wins in the End."

Curl issue retrieving passed back GET parameters

I am working with an OAuth API. Originally, I was making a header redirect once I received my $token than aggregating all of theGET parameters that were passed back to me. I'm trying to implement curl instead so I don't have to redirect back and forth. My problem is, I don't know how to retrieve the returned GET parameters after making my curl request. Here's my code
$qry_str = "?oauth_token=" . $token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, GSAPI_AUTHORIZE_ENDPOINT . $qry_str);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
I've realized I don't need $content. What I need is the GET parameters which should be passed back when I imagine occurs when initiating curl_exec. How do I retrieve these?
-
What you need to do is get the curl request to return the headers as part of the return string. You then need to parse them for the "Location:" tag and use some of the built in parse functions within PHP to get the data you want. Try the below.
$qry_str = "?oauth_token=" . $token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, GSAPI_AUTHORIZE_ENDPOINT . $qry_str);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
if(!$content) echo 'Curl error: ' . curl_error($ch);
preg_match('/Location\:\s(.*)\s/',$content,$matches);
$urlParts = parse_url(trim($matches[1]));
parse_str($urlParts['query'],$queryArray);
The $queryArray variable should now contain all of the query string parameters from the URL in the "Location:" field of the header.
EDIT:
This will work if you hitting a script at http://www.someurl.com/oauth.php and it's then redriecting to http://www.someotherurl.com/somescript.php?param1=x&param2=y.
The result of $queryArray will be array("param1" => 1, "param2" => 2), although I may have completely mis-understood your question...

PHP - How to fire HTTP get request on a secured URL (HTTPS)?

I am trying to fire a HTTP GET request on a secured URL which asks for username and password. This is fine when I am using that from browser but I am not sure how to do that using PHP.
I have tried using the two methods:
1) Using Curl as suggested in here: Make a HTTPS request through PHP and get response
2) Using the file_get_contents as suggested in here: How to send a GET request from PHP?
But the first one didn't give me any response back. And the second one gave me the following error:
failed to open stream: HTTP request failed
And this is my code for the curl:
$url="https://xxxxx.com";
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
and for the file_get_contents:
$url="https://xxxx.com";
$response=file_get_contents($url);
echo $response;
The URL will return a XML response for a API I am testing. Can someone point me to the right direction?
Thanks!
If we focus on the requirement to send a username and password because I suspect that's your main problem, try this
$ch = curl_init();
$url="https://xxxxx.com";
// OR - check with your server's operator
$url="http://xxxxx.com";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// or maybe
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
// - see http://stackoverflow.com/questions/4753648/problems-with-username-or-pass-with-colon-when-setting-curlopt-userpwd
// check the cURL documentation
$output = curl_exec($ch);
$info = curl_getinfo($ch);
// don't forget to check the content of $info, even a print_r($info) is better
// than nothing during debug
curl_close($ch);

See what CURL sends from a PHP script

I'm having dificulties to query a webform using CURL with a PHP script. I suspect, that I'm sending something that the webserver does not like. In order to see what CURL realy sends I'd like to see the whole message that goes to the webserver.
How can I set-up CURL to give me the full output?
I did
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
but that onyl gives me a part of the header. The message content is not shown.
Thanks for all the answers! After all, they tell that It's not possible. I went down the road and got familiar with Wireshark. Not an easy task but definitely worth the effort.
Have you tried CURLINFO_HEADER_OUT?
Quoting the PHP manual for curl_getinfo:
CURLINFO_HEADER_OUT - The request string sent. For this to work, add
the CURLINFO_HEADER_OUT option to the handle by calling curl_setopt()
If you are wanting the content can't you just log it? I am doing something similar for my API calls
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::$apiURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, count($dataArray));
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
$logger->info("Sending " . $dataString);
self::$results = curl_exec($ch);
curl_close($ch);
$decoded = json_decode(self::$results);
$logger->debug("Received " . serialize($decoded));
Or try
curl_setopt($ch, CURLOPT_STDERR, $fp);
I would recommend using curl_getinfo.
<?php
curl_exec($ch);
$info = curl_getinfo($ch);
if ( !empty($info) && is_array($info) {
print_r( $info );
} else {
throw new Exception('Curl Info is empty or not an array');
};
?>

Categories