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

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!

Related

Fantasy Premier League API PHP cURL

I was wondering if you could help me out with a bit of code for a cCURL request using PHP, I'm trying to retrieve data from the fpl api that would show my league standings. The url for the league standings api is - https://fantasy.premierleague.com/api/leagues-classic/my_league_id/standings/?page_new_entries=1&page_standings=1 I can see the data via the browser but when I try to retrieve it with a curl request with PHP it comes back with a 403 error with the message "Authentication credentials were not provided". That would mean that I would need login credentials to retrieve it.
After looking into it using dev tools and postman, I now know that I need to get a csrf token by logging in then save the token to use when I make the request for the league standings. I have no idea how to go about this, I kind of do but I would really appreciate if someone could give it a go for me.
What I would need to do is make a POST request to https://users.premierleague.com/accounts/login/ with this form data -
"login" => "my_email",
"password" => "my_password",
"app" => "plfpl-web",
"redirect_uri" => "https://fantasy.premierleague.com/",
After making the request I would need to capture the csrf token cookie, which I believe would be in the hidden input with the name - "csrfmiddlewaretoken" and save it in a variable.
Once getting the token and saving it, I would then make a GET request to https://fantasy.premierleague.com/api/leagues-classic/my_league_id/standings/ with placing the csrf token variable that I saved into the headers and then json decode that data so I'm able to echo out the league details.
I'm pretty sure that's how to do it but I'm not that great at PHP and was wondering if there is any savour out there that could help a brother out. Any help would be much appreciated :)
I've started with the first part, making the initial post request, but have had no luck in returning the token. Here's my code so far -
<?php
$cookie = "cookies.txt";
$url = 'https://users.premierleague.com/accounts/login/';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
// var_dump($response);
$dom = new DOMDocument;
#$dom->loadHTML($response);
$tags = $dom->getElementsByTagName('input');
for($i = 0; $i < $tags->length; $i++) {
$grab = $tags->item($i);
if($grab->getAttribute('name') === 'csrfmiddlewaretoken') {
$token = $grab->getAttribute('value');
}
}
echo $token;
?>
<?php
// id of the league to show
$league_id = "your_league_id";
// set the relative path to your txt file to store the csrf token
$cookie_file = realpath('your_folder_dir_to_the_txt_file/cookie.txt');
// login url
$url = 'https://users.premierleague.com/accounts/login/';
// make a get request to the official fantasy league login page first, before we log in, to grab the csrf token from the hidden input that has the name of csrfmiddlewaretoken
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
$dom = new DOMDocument;
#$dom->loadHTML($response);
// set the csrf here
$tags = $dom->getElementsByTagName('input');
for($i = 0; $i < $tags->length; $i++) {
$grab = $tags->item($i);
if($grab->getAttribute('name') === 'csrfmiddlewaretoken') {
$token = $grab->getAttribute('value');
}
}
// now that we have the token, use our login details to make a POST request to log in along with the essential data form header fields
if(!empty($token)) {
$params = array(
"csrfmiddlewaretoken" => $token,
"login" => "your_email_address",
"password" => "your_password",
"app" => "plfpl-web",
"redirect_uri" => "https://fantasy.premierleague.com/",
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
/**
* using CURLOPT_SSL_VERIFYPEER below is only for testing on a local server, make sure to remove this before uploading to a live server as it can be a security risk.
* If you're having trouble with the code after removing this, look at the link that #Dharman provided in the comment section.
*/
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//***********************************************^
$response = curl_exec($ch);
// set the header field for the token for our final request
$headers = array(
'csrftoken ' . $token,
);
}
// finally, we now have everything we need to make the GET request to retrieve the league standings data. Enjoy :)
$fplUrl = 'https://fantasy.premierleague.com/api/leagues-classic/' . $league_id . '/standings/';
curl_setopt($ch, CURLOPT_URL, $fplUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
if(!empty($token)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
$response = curl_exec($ch);
$league_data = json_decode($response, true);
curl_close($ch);
echo '<pre class="card">';
print_r($league_data);
echo '</pre>';
?>

How to pass variables between pages using http headers?

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.

Send message button in facebook bot PAGE

good evening,
I'm already breaking my head for 3 days I'm trying to send a message with the button from a page with a bot made in CURL PHP
I'm trying with CURL and PHP POST GRAPH
without success both of us can help me?
function SendRawResponse($Rawresponse){
$userPageConversation = 't_100005050355547';
$Access_token = "XXXX";
$url = "https://graph.facebook.com/v2.6/".$userPageConversation."/messages?access_token=".$Access_token;
//$url = "https://graph.facebook.com/v2.6/me/messages?access_token=".$Access_token;
$ch = curl_init($url);
$headers = array(
'Content-Type: application/x-www-form-urlencoded',
'charset=utf-8',
);
//curl_setopt($ch, CURLOPT_POSTFIELDS, $Rawresponse);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($Rawresponse));
//curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($Rawresponse));
curl_setopt($ch, CURLOPT_POST, true);
//curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_exec($ch);
$erros = curl_errno($ch);
$response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
var_dump($erros);
var_dump($response);
curl_close($ch);
}
Mensage:
$teste = '{
"message":{
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"Try the postback button!",
"buttons":[
{
"type":"web_url",
"title":"GOOGLE",
"url":"https://www.google.com.br"
}
]
}
}
}}';
SendRawResponse($teste);
erros:
Warning: http_build_query(): Parameter 1 expected to be Array or Object. Incorrect value given
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($Rawresponse)); = Missing message body
According to the docs
you must add domain to the whitelist in FB page settings.
Domains must meet the following requirements to be whitelisted:
Served over HTTPS
Use a fully qualified domain name, such as
https://www.messenger.com/. IP addresses and localhost are not
supported for whitelisting.

POST a form using cURL to a cross-domain url and add form data to local database

After much searching of resources I've not been able to quite achieve what I've been after.
I have a form (index.html) that, on submission, is being added to a database (submit.php). After that, two fields (name and email) are being submitted to a url that is not on the same domain - our clients CRM deals with it.
This works fine, except that the page that is returned at the end of the request is still submit.php and the content is the response from the other url instead of redirecting the header to the location that I have set.
This is what handles the cURLing.
$url = 'https://another.url';
$fields = array(
'name-field' => $name,
'email_address' => $email
);
$post_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
$result = curl_exec($ch);
curl_close($ch);
if ($result){
header('Location: success.html');
}
Any ideas on how I can achieve the redirect after the cURL request?
Thanks all for your support.
$url = "https://another.url?email_address".$email;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
if ($result){
header('Location: success.html');
}

php curl login remote server

I have tried all several methods and approaches to this problem and I'm stumped. I'm trying to log into www.senderscore.org with php. The site's log in is a post form to their index page. I need to do this because I need to lookup several IPs and log the information on a regular basis. I have tried posting with curl but I have had no luck. Every attempt just returns the page as if I did not attempt to log in. If anyone could help out with a code snippet I'd appreciate it very much.
edit: The latest attempt's block of code. this is the code inside a class function.
$username= $this->username;
$password= $this->password;
$url = 'www.senderscore.org/index.php';
$fields = array(
'email'=>$username,
'password'=>$password,
'action'=>"localLogin",
'Submit'=>"Sign in",
'remember'=>'1'
);
$postvars='';
$sep='';
foreach($fields as $key=>$value)
{
$postvars.= $sep.urlencode($key).'='.urlencode($value);
$sep='&';
}
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,$postvars);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($curl);
if ($data === false) {
$data = curl_error($curl);
}
curl_close($curl);
return $data;
Try to look at this script, it should work with post; i haven't tested it:
$username = 'your_username';
$password = 'your_password';
$loginUrl = 'http://www.path-to-login.com/login/';
//init curl
$ch = curl_init();
//Set the URL to work with
curl_setopt($ch, CURLOPT_URL, $loginUrl);
// ENABLE HTTP POST - this is important in your case
curl_setopt($ch, CURLOPT_POST, 1);
//Set the post parameters - make sure to match username and password
curl_setopt($ch, CURLOPT_POSTFIELDS, 'user='.$username.'&pass='.$password);
//Handle cookies for the login
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
//Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
//not to print out the results of its query.
//Instead, it will return the results as a string return value
//from curl_exec() instead of the usual true/false.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute the request (the login)
$store = curl_exec($ch);
//the login is now done and you can continue to get the
//protected content.
//set the URL to the protected file
curl_setopt($ch, CURLOPT_URL, 'http://www.site-logging-into.com/protected/file.zip');
//execute the request
$content = curl_exec($ch);
//save the data to disk
file_put_contents('~/file.zip', $content);

Categories