parsing response POST data from curl_exec call - php

I have the following code block which connects out to a secure service (payment transaction gateway), passes in some fields ($postData) and receives a response ($returnValue).
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://secure.service.com/data');
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
if ($returnValue = curl_exec($ch))
{
$error = curl_error($ch);
}
When I display the contents of $returnValue ... they show as follows:
HTTP/1.0 200 OK Approved Date: Wed, 10 Aug 2011 09:24:15 GMT
Connection: close Content-Type: application/x-www-form-urlencoded
Content-Length: 182
avs_code=X&cvv2_code=P&status_code=1&processor=TEST&auth_code=999999&settle_amount=2000&settle_currency=USD&trans_id=120741127516&auth_msg=TEST+APPROVED&auth_date=2011-08-10+09:24:15
Is there a method or CURL call that breaks apart this result string into its component parts? or is that something I need to write myself? I need to get the response code (200), the approval/decline part (Approved) and the query string (avs_code ....). I tried looking through the curl_getinfo but that is only getting me the HTTP Response code, not the approval/decline or the query string values.
I'm a novice at PHP so please let me know if I'm missing an obvious method call or CURL parameter.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_COOKIE, "");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
$header=substr($result,0,curl_getinfo($ch,CURLINFO_HEADER_SIZE));
$body=substr($result,curl_getinfo($ch,CURLINFO_HEADER_SIZE));
curl_close($ch);
Than use something like preg_match_all("/Set-Cookie: (.*?)=(.*?);/i",$header,$res);
See preg_match_all manual

I suggest you look at http://php.net/manual/en/function.http-parse-headers.php manual, if you don't want to install PECL pecl_http - there are usefull user comments. For example:
function http_parse_headers($header) {
$retVal = array();
$fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
foreach ($fields as $field) {
if (preg_match('/([^:]+): (.+)/m', $field, $match)) {
$match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1])));
if (isset($retVal[$match[1]])) {
$retVal[$match[1]] = array($retVal[$match[1]], $match[2]);
} else {
$retVal[$match[1]] = trim($match[2]);
}
}
}
return $retVal;
}
You can parse cookies and post values with http://php.net/manual/ru/function.http-parse-cookie.php (or functions in comments) and http://php.net/manual/en/function.parse-str.php . HTTP protocol is rather transparent.

Related

What on my PHP Curl call do I need to add to read a response's custom headers?

I tried a few several ways to read the responses custom header but have not been able to. I know the response I get is served by nginx and the custom header names start with X-......
$endpoint = 'url here';
$ch = curl_init( $endpoint );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'cbFunc');
$result = curl_exec($ch);
print_r( curl_getinfo($ch ) );
The PHP manual is an excellent reference guide an a good starting point when you run into problems like this.
CURLOPT_HEADERFUNCTION [Set value to] A callback accepting five parameters.
hence
log_headers('init');
$endpoint = 'url here';
$ch = curl_init( $endpoint );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'log_headers');
$result = curl_exec($ch);
$headers=log_headers();
print_r($headers);
function log_headers($ch=false, $headers=false)
{
static $hdrs;
if (is_array($hrs) && $ch===$headers===false) {
return $hdrs[];
} elseif ($ch==='init') {
$hdrs=array();
return 0;
}
$hdrs[]=$headers;
return strlen($headers);
}

How to send JSON data in cURL in PHP

I have rest API of Nodejs Server, I'm trying to make a POST call to it using PHP.
My php code is:
function post_url($apiRoute,$data) {
$request_url = 'http://test-app.herokuapp.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url . $apiRoute);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
echo $data ;
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
I have tried calling this function with diff forms of data:
$g = array("_id" => "111");
$postapiresponse = post_url('/CCTRequest/get',json_encode($g));
OR
$postapiresponse = post_url('/CCTRequest/get',json_encode(array("_id" => "111"));
But on server side which Node.js, when I console log req.body I get data like this:
{ '{"_id":"111"}': '' }
How should I pass the data in PHP so I can get proper obj in node.js i.e:
{ '_id': '111' }
See the PHP document:
http://php.net/manual/en/function.curl-setopt.php
CURLOPT_POST:
TRUE to do a regular HTTP POST. This POST is the normal
application/x-www-form-urlencoded kind, most commonly used by HTML forms.
CURLOPT_POSTFIELDS:
If value is an array, the Content-Type header will be set to multipart/form-data.
So you can pass a query string returned by http_build_query() into CURLOPT_POSTFIELDS:
post_url('/CCTRequest/get', http_build_query($g, null, '&'));
and remove curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));. (In fact, the varieble should be $ch, but you typed $curl, so this line doesn't work.)
In the other way, you can replace curl_setopt($ch, CURLOPT_POST, 1); with
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');, it can prevent the data be encoded automaticlly. And then send json_encode() data.
I have solved by using http_build_query($g, null, '&') for making data.
$g = array("_id" => "111");
$g = http_build_query($g, null, '&');
$postapiresponse = post_url('/CCTRequest/get', $g);
You have a typo in the code, which will prevent it setting the header $curl should be $ch:
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
You also need CURLOPT_RETURNTRANSFER uncommented.
function post_url($apiRoute, $data) {
$request_url = 'www.example.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url . $apiRoute);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}

cURL can't get content of specific website

I try to get the content of this website with cURL
www.mytischtennis.de/public/
but it gets no body response. With many other websites the code works:
<?php
$output = grabPage(
"http://www.mytischtennis.de/public/"
//"http://www.spiegel.de" //this page and many other pages are working
);
if (is_array($output)) {
var_dump($output);
} else {
echo $output;
}
function grabPage($url)
{
$ch = curl_init();
$cookiePath= dirname(__FILE__) . "\cookie.txt";
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_MAXREDIRS, 50);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_TIMEOUT, 40);
curl_setopt($ch, CURLOPT_COOKIE, 'CFID=c7a592d8-5798-4471-9af4-4c4d954d03cd; cfid=c7a592d8-5798-4471-9af4-4c4d954d03cd; MYTT_COOKIESOK=1; CFTOKEN0=; cftoken=0; SRV=74');
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiePath);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiePath);
$fpErrors = fopen(dirname(__FILE__) . '\errorlog.txt', 'w');
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, $fpErrors);
curl_setopt($ch, CURLOPT_URL, $url);
ob_start();
$curl_exec = curl_exec($ch);
ob_end_clean();
if ($curl_exec === false) {
echo 'Error: ' . curl_error($ch);
} else {
echo 'Success';
}
var_dump(curl_getinfo($ch));
curl_close($ch);
return $curl_exec;
}
I tried to read a fiddler/wireshark dump of a browser request to this website. But I can't figure out which of that many requests and which parameters are necessary to get the content.
You can test cURL with the url www.mytischtennis.de/public/ also on this website:
http://onlinecurl.com/
You need to accept gzip encoding in the response by sending the appropriate HTTP header in the request:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept-Encoding: gzip'));
Now your answer from the server might or might not be gziped. The proper way to check that is to interpret the Content-Encoding HTTP header in the response. But you can also do it quick and dirty like this:
$content = #gzdecode($curl_exec);
return $content !== false ? $content : $curl_exec;

Getting executed URL from CURL

I have a Affiliate URL Like http://track.abc.com/?affid=1234
open this link will go to http://www.abc.com
now i want to execute the http://track.abc.com/?affid=1234 Using CURL
and now how i can Get http://www.abc.com
with Curl ?
If you want cURL to follow redirect headers from the responses it receives, you need to set that option with:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
You may also want to limit the number of redirects it follows using:
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
So you'd using something similar to this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://track.abc.com/?affid=1234");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($ch);
Edit: Question wasn't exactly clear but from the comment below, if you want to get the redirect location, you need to get the headers from cURL and parse them for the Location header:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://track.abc.com/?affid=1234");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, true);
$data = curl_exec($ch);
This will give you the headers returned by the server in $data, simply parse through them to get the location header and you'll get your result. This question shows you how to do that.
I wrote a function that will extract any header from a cURL header response.
function getHeader($headerString, $key) {
preg_match('#\s\b' . $key . '\b:\s.*\s#', $headerString, $header);
return substr($header[0], strlen($key) + 3, -2);
}
In this case, you're looking for the value of the header Location. I tested the function by retrieving headers from a TinyURL, that redirects to http://google.se, using cURL.
$url = "http://tinyurl.com/dtrkv";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
$location = getHeader($data, 'Location');
var_dump($location);
Output from the var_dump.
string(16) "http://google.se"

how to run: url from php = run from browser

How to run url from php script in the same way (exactly the same behaviour) as in browser when i run url from address bar. I mean with the same header data, cookies and additional data which browser send. How to add this data in php.
I need this cause when I logged in, answers from this 2 cases are not the same:
in browser I still logged in and this is correct
from php run I am logged OUT - not correct
I've tried file_get_contents nad curl (from here) but it doesn't work properly - response is still different.
I'm calling http://127.0.0.1/check.html and here is function check:
public function check(){
echo 'begin';
// $total_rows = file_get_contents('https://127.0.0.1:8443/example.html?shopId=121');
$total_rows = $this->getUrl('https://127.0.0.1:8443/example.html', '121');
print_r($total_rows);
echo 'end';
}
function getUrl($url, $shopId ='') {
$post = 'shopId=' . $shopId;
$ch = curl_init();
$cookie_string="";
foreach( $_COOKIE as $key => $value ) {
$cookie_string .= "$key=$value;";
};
$cookie_string .= "JSESSIONIDSSO=66025D1CC9EF39ED7F5DB024B6026C61";
// echo $cookie_string;;
$ch = curl_init();
curl_setopt($ch,CURLOPT_COOKIE, $cookie_string);
// curl_setopt($ch, CURLOPT_PORT, 8443);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
// curl_setopt ($ch, CURLOPT_CAINFO, dirname(__FILE__)."/../../files/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
// curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Secure Content-Type: text/html; charset=UTF-8"));
// curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: 127.0.0.1:8443'));
$ret = curl_exec($ch);
curl_error ($ch );
curl_close($ch);
return $ret;
}
Try it:
http://www.lastcraft.com/browser_documentation.php
Or that:
http://sourceforge.net/projects/snoopy/
Or that:
php curl: how can i emulate a get request exactly like a web browser?
Hope help
You can execute the cron job using your PHP script to execute the other script.

Categories