PHP Curl How to extract header's - php

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://test.com");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'x=32423');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
if(curl_exec($ch) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
'OK';
}
This is what outputted,when i run this page
access_token=AAAdsfsdfds32432fadfcazdfadsfadsfdas
How do i extract this and pass it a variable?

There is a typo in your postfields. The postfields should be as follows:
curl_setopt($ch, CURLOPT_POSTFIELDS, array('x'=>'32423'));
instead of:
curl_setopt($ch, CURLOPT_POSTFIELDS, 'x=32423'');

First off, you need to change your CURLOPT_HEADERS to true, and you need
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
and
$result=curl_exec($ch)
if( $result=== false)
Then, according to an answer I saw elsewhere on SO, this should get you the headers:
list($headers,$content) = explode("\r\n\r\n",$result,2);
foreach (explode("\r\n",$headers) as $hdr)
print_r($hdr); //see what it gives you and then edit this accordingly.
echo $content;

Sounds like you just want
$token = end(explode('=', $access_token_string));

Related

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;

php - curl empty response while browser display json output

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://itunes.apple.com/search?term=Clean%20Bandit%20-%20Rather%20Be&entity=song&limit=10&lang=fr_fr');
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(curl_errno($ch))
echo 'Curl error: '.curl_error($ch);
$CurResult = curl_exec($ch);
curl_close($ch);
echo 'Result:'.$CurResult;
$url = 'https://itunes.apple.com/search?term=Clean%20Bandit%20-%20Rather%20Be&entity=song&limit=10&lang=fr_fr';
$content = file_get_contents($url);
print_r($content);
Use this code to get the response curl is not needed in this case
from php manual
curl_errno()
does not return true or false, it returns error number 0, if no errors.
so you either change the condition to
if(curl_errno($ch)!=0)
or use curl_error()
if(curl_error($ch)!=''){
echo "error: ".curl_error($ch);
}
http://se2.php.net/manual/en/function.curl-errno.php

How to read CURL POST on remote server?

This is my cURL POST function:
public function curlPost($url, $data)
{
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
}
$this->curlPost('remoteServer', array(data));
How do I read the POST on the remote server?
The remote server is using PHP... but what var in $_POST[] should I read
for e.g:- $_POST['fields'] or $_POST['result']
You code works but i'll advice you to add 2 other things
A. CURLOPT_FOLLOWLOCATION because of HTTP 302
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
B. return in case you need to output the result
return $result ;
Example
function curlPost($url, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return $result;
}
print(curlPost("http://yahoo.com", array()));
Another Example
print(curlPost("http://your_SITE", array("greeting"=>"Hello World")));
To read your post you can use
print($_REQUEST['greeting']);
or
print($_POST['greeting']);
as a normal POST request ... all data posted can be found in $_POST ... except files of course :) add an &action=request1 for example to URL
if ($_GET['action'] == 'request1') {
print_r ($_POST);
}
EDIT: To see the POST vars use the folowing in your POST handler file
if ($_GET['action'] == 'request1') {
ob_start();
print_r($_POST);
$contents = ob_get_contents();
ob_end_clean();
error_log($contents, 3, 'log.txt' );
}

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.

parsing response POST data from curl_exec call

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.

Categories