How to pass variables between pages using http headers? - php

I'm trying to pass an authorization token between two pages of my application and would like to do so using HTTP headers, however my code is not working as expected.
I've tried retrieving the header using getallheaders() from the second page however the header that I pass it from the first page is not present in the list.
This is the flow of what I'm doing
Placing token into the header array
Executing the POST call
Redirecting to second page using header("Location:")
(on second page) Checking the headers
//placing token into header/////////////////////////////////////////
$token_header['Authorization'] = $accessTokenResult['access_token'];
$header = array();
foreach($token_header as $key => $parsed_urlvalue)
{
$header[] = "$key: $parsed_urlvalue";
}
//sending the request//////////////////////////////////////////////
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_URL, "./custom_request.php");
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
curl_close($ch);
//redirecting to the second page////////////////////////////////////
header("Location: custom_request.php");
die("Redirected to custom request page");
Other page
$headers_recieved = getallheaders();
echo $headers_recieved['Authorization'];
However I'm getting an invalid index error since 'Authorization' is not present.

Related

i need to know how to call curl with api key parameter with given command

i have curl command provided by some developer, i need to know how to call it in php.
Command is :
curl -H "x-api-key: xxxxxxxxxxxxxxxxxxxxxx"
"https://api.civicengine.com/office-
holders?address=1060+W+Addison+Chicago+IL"
i have written this
$data['api-key']='xxxxxxxxxxxxxxxxxxxxx';
/*$data['host']='https://api.civicengine.com';*/
$url='https://api.civicengine.com/office-holders?address=1060+W+Addison+Chicago+IL';
$ch = curl_init();
// set basic auth
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// set header accept
$headers = array('Accept:application/json', 'Accept-Language:en_US',"Authorization: Bearear xxxxxxxxxxxxxxxxxxxx");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// set mode to POST
curl_setopt($ch, CURLOPT_POST, 1);
// add post fields (1)
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL, $url);
// Execute
print_r($result = json_decode(curl_exec($ch)));die;
i expect result but its giving
stdClass Object ( [message] => Authorization header requires 'Credential' parameter. Authorization header requires 'Signature' parameter. Authorization header requires 'SignedHeaders' parameter. Authorization header requires existence of either a 'X-Amz-Date' or a 'Date' header. Authorization=FLUdjGvxuJ9liutivB0Ll5LW2t2xmv31lvK2guQi )
you forgot to add the x-api-key header to your php curl_ code. also your php code is altering the Accept Accept-Language, and Authorization header, your curl invocation proves that's not needed, and they may be incorrect to boot (idk), get rid of them while debugging (and once everything is working, you may add them back and check that they don't break anything..)
Follow this method to send api_key in header of API REQUEST
// Collection object
$ch = curl_init($url);
$headers = array(
"APIKEY: PUT_HERE_API_KEY",
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml"
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlreq);
$result = curl_exec($ch); // execute
$result;
//show response
curl_close($ch);

XML in curl PHP

I am calling an API using CURL.
When I run it directly in browser or via ajax request it runs well and gives xml output.The Api am calling stores the xml in a database table and would only then work well.
However when I call it via PHP curl their table is not getting updated.
The code am doing it with PHP curl is
curl_setopt($ch, CURLOPT_URL, $api);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
$headers = array();
$headers[] = "Accept: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
Sample URL : http://example.com/code=x05a&businessKeyValue=8519ada0-9e2f-e265-8698-5b6145af9704&entity=funded_program_concession&parameters=fpc_funded_program_concession_id%7C8519ada0-9e2f-e265-8698-5b6145af9704&parameters=fps_funded_program_subsidy_id%7Cf320f2d9-7c6a-0b56-2940-5b61147a0f3d
If I open this link which opens it in browser, it works good, but if I run it via curl the API is not receiving xml content.
How can I resolve this issue?
$api='http://example.com/code=x05a&businessKeyValue=8519ada0-9e2f-e265-8698-5b6145af9704&entity=funded_program_concession&parameters=fpc_funded_program_concession_id%7C8519ada0-9e2f-e265-8698-5b6145af9704&parameters=fps_funded_program_subsidy_id%7Cf320f2d9-7c6a-0b56-2940-5b61147a0f3d';
$ch = curl_init();
$headers = array();//put your headers only if you need them
curl_setopt($ch, CURLOPT_URL, $api);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result= curl_exec($ch);
return $result;
This should work for you. Inside your headers array make sure you put the headers you need and not extra. This is a simple curl, get call so i guess the above code will work without any trouble.
If you want to accept xml then you can got for Accept:application/xml or Accept:application/xhtml+xml
If the above methods don't work provide us with your error.
echo 'Curl error: ' . curl_error($ch);
Add the above line as a breaking point in your code and see what's the error.

How do I fix this Bitly oAuth 'single header' error?

Context: I have a WordPress plugin that allows users to authenticate with Bitly so that they can use link shortening features if they desire to do so.
Bitly requires one callback URL to be stored in the app settings, so I created a standalone script on my server that processes the authentication process. The overall handshake actually looks something like this:
The user clicks a link taking them to the Bitly authorization page for my app.
If they agree, they are forwarded to my script with a code.
My script exchanges that code to Bitly for another code.
Once the codes are all acquired, it reaches out to the user's domain to store the codes and to retreive the URL of the options page on that user's URL so that we can redirect the user back home.
We then redirect the user back to the options page that they had just clicked away from.
Problem: However, a very small handful of users are getting the following error just prior to the authentication process being complete:
Warning: Header may not contain more than a single header, new line
detected in /home/warfarep/public_html/bitly_oauth.php on line 72.
Sample Code:
function sw_file_get_contents_curl($url){
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_FAILONERROR, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
$cont = #curl_exec($ch);
$curl_errno = curl_errno($ch);
curl_close($ch);
if ($curl_errno > 0) {
return 0;
}
return $cont;
}
// Check if this is the first pass and we have the generic code
if(isset($_GET['code'])):
// Retreive the information
$code = $_GET['code'];
$client_ID = 'blahblahblah';
$client_secret = 'blahblahblah';
$redirect_url = 'blahblahblah';
$state = $_GET['state'];
$url = 'https://api-ssl.bitly.com/oauth/access_token';
$fields = array(
'code' => urlencode($code),
'client_id' => urlencode($client_ID),
'client_secret' => urlencode($client_secret),
'redirect_uri' => urlencode($redirect_url),
'state' => urlencode($state)
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_HTTPHEADER, array('Accept: application/json'));
//execute post
$response = curl_exec($ch);
//close connection
curl_close($ch);
$response = json_decode($response , true);
$ajax_url = $state .= '?action=sw_bitly_oauth&access_token='.$response['access_token'].'&login='.$response['login'];
$wp_response = sw_file_get_contents_curl($ajax_url);
$wp_response = rtrim($wp_response , '0');
header('Location: '.$wp_response);
^^^^^^ This is line 72 from the error message
endif;
Question: Is there anything that you can see that would prevent headers from already being sent prior to the redirect on line 72? How do I fix this Bitly oauth "single header" error? Thanks!

Redirect Curl request with data

I have a PHP curl request which works - However, if i set CURLOPT_FOLLOWLOCATION as 1, the Curl post is submitted with the postdata, the redirected page HTML is captured and posted on my localserver.
The entire redirect is contained within my local server and it doesnt actually transfer me across to the redirection itself with the data (which is what i want). After a few seconds of the html being downloaded on my post.php, it redirects to a page not found.
However, if i set the CURLOPT_FOLLOWLOCATION as 0 and then fetch the correct URL and then redirect it through header("Location: $redirect"); - it transfers fine but there no more data being transferred.
What would be the best way of transferring that data to the new header location.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'postdata=' . urlencode(xmlGrab()));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
// Download the given URL, and return output
$output = curl_exec($ch);
$headers = substr($output, 0, $curl_info["header_size"]); //split out header
$redirect = curl_getinfo($ch)['redirect_url'];
header('HTTP/1.1 307 Temporary Redirect');
header("Location: $redirect");
// Close the cURL resource, and free system resources
curl_close($ch);
Example Scenario:
User Submits a post http://localhost:8888/post.php
Post.php contains a connection to google.co.uk
Post.php connects and makes a post to google.co.uk
The request downloads google.co.uk?q=blahblah to post.php
post.php looks exactly like google.co.uk?q=blahblah
3 seconds later, it redirects to http;//localhost:8888/?q=blahblah
Check the value of $redirect.
If it's a relative url you have to prepend the protocol+hostname+etc to the url, otherwise you'll end up on your local server.

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"

Categories