Curl Post with a Loop (Field taken from a DB) - php

I need your help.
Actually I'm doing a CURL post with X-Wsse auth and posting only 2 arguments, ID and Phone.
Everything is ok.
Now I need to pass a list of ID and phones. In which way I can do this? Post a file directly? Using a loop?
I have a csv file, but for simplify I upload this file on a DB, so I can take directly from there.
This is the actual code.
<?php
function make_nonce() {
$chars = "123456789abcdefghijklmnopqrstuvwxyz";
$random = "" . microtime();
$random .= mt_rand();
$mi = strlen($chars) - 1;
for ($i = 0; $i < 10; $i++) {
$random .= $chars[mt_rand(0, $mi)];
}
$nonce = md5($random);
return $nonce;
}
function make_token($username, $password) {
$nonce = make_nonce();
$ts = date ( 'Y-m-d\TH:i:sP', time() + 290 );
$digest = base64_encode(sha1($nonce.$ts.$password, true));
return sprintf('UsernameToken Username="%s",
PasswordDigest="%s",Nonce="%s", Created="%s"',
$username, $digest, $nonce, $ts);
}
$token = make_token("username", "password"); // ### GENERO IL TOKEN
$headers = array( 'Content-type: application/x-www-form-urlencoded;
charset=UTF-8','Accept-Charset : UTF-8', 'X-Wsse :' . $token);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://URL');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"phoneNumber=38452136&idPratica=745");
curl_exec ($ch);
var_dump($ch);
curl_close ($ch);
?>
I have a list of 1000 phonenumber and relatives idpratica (ID).
What can I do?
I know the way for doing with just one record.
$fields = array(
'phoneNumber' => '38452136',
'idPratica' => '745'
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
and then use
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
Please help me

Related

Shopify GraphQL Error "Parse error on \":\" (COLON) at [2, 35]" With PHP

Greetings I have a problem with my GraphQL I don't know how to pass data to my GraphQL without getting
Error Message: "Parse error on ":" (COLON) at [2, 35]"
here is what I'm trying to pass product variant id data and get some response here is the example of what I'm trying to do and my function for graphql
$variantId = (isset($data->variantId) && !empty($data->variantId)) ? strip_tags($data->variantId) : "";
if(empty($variantId)){
$result['error'] = "Product id not specified!";
}
$query = array("query" => '{
productVariant(id: '. ($variantId) .') {
availableForSale
}
}');
$variants = shopify_gql_call($_SESSION['access_token'], $_SESSION['shop_name'], $query);
if( isset($variants['response']) && !empty($variants['response']) ){
$result[] = $variants['response'];
}else{
$result['error'] = "Variants not found!";
}
function shopify_gql_call($token, $shop, $query = array()) {
// Build URL
$url = "https://" . $shop . ".myshopify.com" . "/admin/api/".getenv('API_DATE')."/graphql.json";
// Configure cURL
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_MAXREDIRS, 3);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
// curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 3);
// curl_setopt($curl, CURLOPT_SSLVERSION, 3);
curl_setopt($curl, CURLOPT_USERAGENT, 'My New Shopify App v.1');
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
// Setup headers
$request_headers[] = "";
$request_headers[] = "Content-Type: application/json";
if (!is_null($token)) $request_headers[] = "X-Shopify-Access-Token: " . $token;
curl_setopt($curl, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($query));
curl_setopt($curl, CURLOPT_POST, true);
// Send request to Shopify and capture any errors
$response = curl_exec($curl);
$error_number = curl_errno($curl);
$error_message = curl_error($curl);
// Close cURL to be nice
curl_close($curl);
// Return an error is cURL has a problem
if ($error_number) {
return $error_message;
} else {
// No error, return Shopify's response by parsing out the body and the headers
$response = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
// Convert headers into an array
$headers = array();
$header_data = explode("\n",$response[0]);
$headers['status'] = $header_data[0]; // Does not contain a key, have to explicitly set
array_shift($header_data); // Remove status, we've already set it above
foreach($header_data as $part) {
$h = explode(":", $part, 2);
$headers[trim($h[0])] = trim($h[1]);
}
// Return headers and Shopify's response
return array('headers' => $headers, 'response' => $response[1]);
}
}
I strongly suggest the use of https://packagist.org/packages/shopify/shopify-api instead of implementing your own function/http requests.
Your query should be something like this
query anynamehere($id: ID!){
productVariant(id:$id){
availableForSale
}
}
and then you submit the ID as part of another entry of the array, check the example below:
$query = [
"query" =>
'query anynamehere($id: ID!){
productVariant(id:$id){
availableForSale
}
}',
"variables" => [
'id' => $variantId
]
];
You should never concatenate the values as part of the query string (unless you want to deal with a lot of injection issues). Check more info about variables here https://graphql.org/learn/queries/

Binance Pay: "Signature for this request is not valid" error with PHP cURL

I'm using PHP cURL in order to connect to Binance Pay API. I get the following error:
{"status":"FAIL","code":"400002","errorMessage":"Signature for this request is not valid."}
Here is my code:
// Generate nonce string
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$nonce = '';
for($i=1; $i <= 32; $i++)
{
$pos = mt_rand(0, strlen($chars) - 1);
$char = $chars[$pos];
$nonce .= $char;
}
$ch = curl_init();
$timestamp = round(microtime(true) * 1000);
// Request body
$request = array(
"merchantTradeNo" => "12485634875fJhdd56",
"totalFee" => 15,
"productDetail" => "productDetail",
"currency" => "BUSD",
"returnUrl" => "",
"tradeType" => "WEB",
"productType" => "productType",
"productName" => "ProductName"
);
$json_request = json_encode($request);
$payload = $timestamp."\n".$nonce."\n".$json_request."\n";
$signature = strtoupper(hash_hmac('SHA512',$payload,$binance_pay_secret));
$headers = array();
$headers[] = "Content-Type: application/json";
$headers[] = "BinancePay-Timestamp: $timestamp";
$headers[] = "BinancePay-Nonce: $nonce";
$headers[] = "BinancePay-Certificate-SN: $binance_pay";
$headers[] = "BinancePay-Signature: $signature";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, "https://bpay.binanceapi.com/binancepay/openapi/order");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$result = curl_exec($ch);
if (curl_errno($ch)) { echo 'Error:' . curl_error($ch); }
curl_close ($ch);
Regarding the documentation, everything seems ok, but it's not, so there is something wrong. Any idea? Thanks!
In python (and most likely in PHP as well) json encode is slightly modifying the request json by adding spaces and/or escaping quotes. The Binance Pay API requires the json string to be exactly how it is in the documentation. That is, with no extra spaces.
You forgot to add this
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_request);

Workflow Max add job via API

I'm trying to add a job to the Workflow Max API. I seem to be hitting the API but I keep getting the error message:
Message not in expected format. The following required element was missing - Job/ClientID
I'm sure that the client ID is added but something seems to be wrong. This is the code:
function post_job_to_workflow_max($job_data) {
// configure our connection to the api
$api_token = 'API_KEY';
$acc_key = 'ACC_TOKEN';
$url = 'https://api.workflowmax.com/job.api/add?apiKey=' . $api_token . '&accountKey=' . $acc_key;
// Job data must match the format required by WorkflowMax
// currently accepts XML data
// see: https://www.workflowmax.com/api/job-methods#POST%20add
$xml = new SimpleXMLElement("<Job></Job>");
$xml->addChild('Name', $job_data[0]);
$xml->addChild('Description', $job_data[1]);
$xml->addChild('ClientID', 18754031);
// $clientID = $xml->addChild('Client');
// $clientID->addChild('ID', 18754031);
// $clientID->addChild('Name', "TEST CLIENT");
$xml->addChild('State', 'Planned');
$xml->addChild('StartDate', $job_data[2]);
$xml->addChild('DueDate', $job_data[3]);
// print_r($xml);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/xml',
'Content-Length: ' . strlen($xml->asXML()))
);
$output = curl_exec($ch);
curl_close($ch);
$result = simplexml_load_string($output);
print_r($result);
}
If there's anyone with experience of using WFM, would be good to hear how you approached it.
Thanks
So in answer to my own question, I did finally work this out.
The way I did this was to return the ID of the client from the function I used to post a client to WorkFlow Max. See code:
1) post the client
function post_client_to_workflowmax($client_data) {
// configure our connection to the api
$api_token = 'YOUR_TOKEN';
$acc_key = 'YOUR_KEY';
$url = 'https://api.workflowmax.com/client.api/add?apiKey=' . $api_token . '&accountKey=' . $acc_key;
// Client data must match the format required by WorkflowMax
// currently accepts XML data
// These indexes match up with how the data has been stored
// see: https://www.workflowmax.com/api/client-methods#POST%20add
$xml = new SimpleXMLElement("<Client></Client>");
$xml->addChild('Name', htmlspecialchars($client_data[2]));
$xml->addChild('Email', htmlspecialchars($client_data[9]));
$xml->addChild('Phone', htmlspecialchars($client_data[10]));
$xml->addChild('Address', htmlspecialchars($client_data[3]) . ' ' . htmlspecialchars($client_data[4]));
$xml->addChild('City', htmlspecialchars($client_data[5]));
$xml->addChild('Postcode', htmlspecialchars($client_data[7]));
$xml->addChild('Country', htmlspecialchars($client_data[8]));
$xml->addChild('IsProspect', 'No');
$contacts = $xml->addChild('Contacts');
$contact = $contacts->addChild('Contact');
$name = $contact->addChild('Name', htmlspecialchars($client_data[0]) . ' ' . htmlspecialchars($client_data[1]));
// POST request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/xml',
'Content-Length: ' . strlen($xml->asXML()))
);
$output = curl_exec($ch);
curl_close($ch);
// Create an array from the data that is sent back from the API
$result = simplexml_load_string($output);
$clientID = NULL;
// here we get the ID created for this client and pass it into the variable $clientID
foreach($result->Client as $k => $v) {
$clientID = $v->ID;
}
return $clientID;
}
We then get that ID passed into our job posting function like so:
2) post a job to WFM
function post_job_to_workflow_max($job_data, $clientID) {
// configure our connection to the api
$api_token = 'YOUR_TOKEN';
$acc_key = 'YOUR_KEY';
$url = 'https://api.workflowmax.com/job.api/add?apiKey=' . $api_token . '&accountKey=' . $acc_key;
// Job data must match the format required by WorkflowMax
// currently accepts XML data
// see: https://www.workflowmax.com/api/job-methods#POST%20add
$xml = new SimpleXMLElement("<Job></Job>");
$xml->addChild('ClientID', $clientID);
$xml->addChild('Name', htmlspecialchars($job_data[0]));
$xml->addChild('Description', htmlspecialchars($job_data[1]));
$xml->addChild('State', 'Planned');
$xml->addChild('StartDate', htmlspecialchars($job_data[2]));
$xml->addChild('DueDate', htmlspecialchars($job_data[3]));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/xml',
'Content-Length: ' . strlen($xml->asXML()))
);
$output = curl_exec($ch);
curl_close($ch);
$result = simplexml_load_string($output);
}
And then calling these functions looks something like this:
$id = post_client_to_workflowmax($client);
post_job_to_workflow_max($job, $id);
Where $client must be an array of data. This worked for my case but might not work for your particular case so you may need to edit the fields etc.
Hopefully this helps someone who is stuck with the same problem. Not the most elegant code but it gets the job done.

RingCentral PHP FaxOut API example

I just started looking at the RingCentral API
I am a little confused on how they expect the data.
I tried first with curl using:
$url = ' https://service.ringcentral.com/faxapi.asp';
$faxData = array();
$faxData['Username'] = 'xxxxxxxx';
$faxData['Password'] = 'xxxxxxxx';
$faxData['Recipient'] = $faxNumber.'|TEST';
$faxData['Attachment'] = ROOT_PATH.$fileLocation;
// build url encoded string
$fields_string='';
foreach($faxData as $key=>$value) {
$fields_string .= $key.'='.urlencode($value).'&';
}
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($faxData));
curl_setopt($ch,CURLOPT_POSTFIELDS, $faxData);
//execute post
$result = curl_exec($ch);
$err = curl_errno ( $ch );
$errmsg = curl_error ( $ch );
$header = curl_getinfo ( $ch );
$httpCode = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
//close connection
curl_close($ch);
Then I tried sending as an email using the number#ringcentral.com and I still am unable to get this to work at all. Their support site is useless as I see many unanswered questions but I have no choice and need to get this working.
I am hoping someone has done this in PHP and can provide me with an example or point me in the right path.
I was able to get the original code to work doing two things:
(1) Removing the leading space from $url:
# Original
$url = ' https://service.ringcentral.com/faxapi.asp';
# New
$url = 'https://service.ringcentral.com/faxapi.asp';
(2) Ensuring ROOT_PATH began with a # as specified in the PHP documentation for CURLOPT_POSTFIELDS at http://php.net/manual/en/function.curl-setopt.php.
cURL and Guzzle Examples
Here are some examples using cURL and Guzzle verified to work.
cURL Example
function ringcentral_faxout_api_via_curl($username,$password,$recipient,$file,$coverpagetext) {
$request = curl_init('https://service.ringcentral.com/faxapi.asp');
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_POSTFIELDS, array(
'username' => $username,
'password' => $password,
'recipient' => $recipient,
'attachment' => '#' . realpath($file),
'coverpagetext' => $coverpagetext
));
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($request);
curl_close($request);
return $response;
}
$username = 'myusername';
$password = 'mypassword';
$recipient = 'myrecipient';
$file = '/path/to/myfile';
$result = ringcentral_faxout_api_via_curl( $username, $password, $recipient, $file, 'PHP FaxOut Via cURL');
Guzzle Example
use GuzzleHttp\Client;
function ringcentral_faxout_api_via_guzzle($username,$password,$recipient,$file,$coverpagetext) {
$client = new Client();
$response = $client->post('https://service.ringcentral.com/faxapi.asp', [
'body' => [
'username' => $username,
'password' => $password,
'recipient' => $recipient,
'attachment' => fopen($file, 'r'),
'coverpagetext' => $coverpagetext
]
]);
return $response->getBody();
}
$username = 'myusername';
$password = 'mypassword';
$recipient = 'myrecipient';
$file = '/path/to/myfile';
$result = ringcentral_faxout_api_via_guzzle( $username, $password, $recipient, $file, 'PHP FaxOut Via Guzzle');
New RingCentral API
Also check out the newer RingCentral Platform API which has a much more comprehensive API for faxing and other capabilities documented here: https://developers.ringcentral.com/api-and-docs.html
function fetch_url_post($url, $variable_array){
$fields_string = "";
//set POST variables
#$url = 'http://domain.com/get-post.php';
foreach($variable_array as $key => $value){
$fields[$key] = urlencode($value);
}
//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);
//execute post
$result = curl_exec($ch);
return $result;
//close connection
curl_close($ch);
}
$url = ' https://service.ringcentral.com/faxapi.asp';
$faxData = array();
$faxData['Username'] = 'xxxxxxxx';
$faxData['Password'] = 'xxxxxxxx';
$faxData['Recipient'] = $faxNumber.'|TEST';
$faxData['Attachment'] = ROOT_PATH.$fileLocation;
echo fetch_url_post($url, $faxData);
make sure ROOT_PATH.$fileLocation; is an absolute and correct path

another twitter oAuth cURL access token request that fails

The following function gives a validation error instead of the token:
failed to validate oAuth signature and token
function request_token()
{
// Set url
$url = $this->site.$this->request_token_path; // http://api.twitter.com/oauth/request_token
// Params to pass to twitter and create signature
$params['oauth_consumer_key'] = $this->consumerKey;
$params['oauth_token'] = '';
$params['oauth_nonce'] = SHA1(time());
$params['oauth_timestamp'] = time();
$params['oauth_signature_method'] = $this->signatureMethod; // HMAC-SHA1;
$params['oauth_version'] = $this->version; // 1.0
ksort($params);
//print "<pre>"; print_r($params); print "</pre>";
// Create Signature
$concatenatedParams = '';
foreach($params as $k => $v){
$concatenatedParams .= "{$k}={$v}&";
}
$concatenatedParams = substr($concatenatedParams,0,-1);
$signatureBaseString = "POST&".urlencode($url)."&".urlencode($concatenatedParams);
$params['oauth_signature'] = base64_encode(hash_hmac('SHA1', $signatureBaseString, $this->secret."&", TRUE));
// Do cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLINFO_HEADER_OUT, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
$exec = curl_exec ($ch);
$info = curl_getinfo($ch);
curl_close ($ch);
print $exec;
//print "<pre>"; print_r($info); print "</pre>";
}
Below is what Ive put together so far and it works :-)
class Twitauth
{
var $key = '';
var $secret = '';
var $request_token = "https://twitter.com/oauth/request_token";
function Twitauth($config)
{
$this->key = $config['key']; // consumer key from twitter
$this->secret = $config['secret']; // secret from twitter
}
function getRequestToken()
{
// Default params
$params = array(
"oauth_version" => "1.0",
"oauth_nonce" => time(),
"oauth_timestamp" => time(),
"oauth_consumer_key" => $this->key,
"oauth_signature_method" => "HMAC-SHA1"
);
// BUILD SIGNATURE
// encode params keys, values, join and then sort.
$keys = $this->_urlencode_rfc3986(array_keys($params));
$values = $this->_urlencode_rfc3986(array_values($params));
$params = array_combine($keys, $values);
uksort($params, 'strcmp');
// convert params to string
foreach ($params as $k => $v) {$pairs[] = $this->_urlencode_rfc3986($k).'='.$this->_urlencode_rfc3986($v);}
$concatenatedParams = implode('&', $pairs);
// form base string (first key)
$baseString= "GET&".$this->_urlencode_rfc3986($this->request_token)."&".$this->_urlencode_rfc3986($concatenatedParams);
// form secret (second key)
$secret = $this->_urlencode_rfc3986($this->secret)."&";
// make signature and append to params
$params['oauth_signature'] = $this->_urlencode_rfc3986(base64_encode(hash_hmac('sha1', $baseString, $secret, TRUE)));
// BUILD URL
// Resort
uksort($params, 'strcmp');
// convert params to string
foreach ($params as $k => $v) {$urlPairs[] = $k."=".$v;}
$concatenatedUrlParams = implode('&', $urlPairs);
// form url
$url = $this->request_token."?".$concatenatedUrlParams;
// Send to cURL
print $this->_http($url);
}
function _http($url, $post_data = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
if(isset($post_data))
{
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
}
$response = curl_exec($ch);
$this->http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$this->last_api_call = $url;
curl_close($ch);
return $response;
}
function _urlencode_rfc3986($input)
{
if (is_array($input)) {
return array_map(array('Twitauth', '_urlencode_rfc3986'), $input);
}
else if (is_scalar($input)) {
return str_replace('+',' ',str_replace('%7E', '~', rawurlencode($input)));
}
else{
return '';
}
}
}
not sure if your still looking into this, or if it will work for you, but i had a similar setup and had the same issue. I eventually found i was urlencoding one to many times.
Try commenting out this section:
$keys = $this->_urlencode_rfc3986(array_keys($params));
$values = $this->_urlencode_rfc3986(array_values($params));
$params = array_combine($keys, $values);
Worked for me, so maybe it will help.
I'll admit this isn't really an answer, but if you can, use the PECL OAuth package. Rasmus Lerdorf wrote a tutorial on how to use it and it got me around this same issue.
I faced same issue, what I was missing is passing header in to the curl request. As shown in this question, I was also sending the $header = array('Expect:'), which was the problem in my case. I started sending signature in header with other data as below and it solved the case for me.
$header = calculateHeader($parameters, 'https://api.twitter.com/oauth/request_token');
function calculateHeader(array $parameters, $url)
{
// redefine
$url = (string) $url;
// divide into parts
$parts = parse_url($url);
// init var
$chunks = array();
// process queries
foreach($parameters as $key => $value) $chunks[] = str_replace('%25', '%', urlencode_rfc3986($key) . '="' . urlencode_rfc3986($value) . '"');
// build return
$return = 'Authorization: OAuth realm="' . $parts['scheme'] . '://' . $parts['host'] . $parts['path'] . '", ';
$return .= implode(',', $chunks);
// prepend name and OAuth part
return $return;
}
function urlencode_rfc3986($value)
{
if(is_array($value)) return array_map('urlencode_rfc3986', $value);
else
{
$search = array('+', ' ', '%7E', '%');
$replace = array('%20', '%20', '~', '%25');
return str_replace($search, $replace, urlencode($value));
}
}

Categories