I'm unable to upload an image to Flickr using the Flickr API. I'm trying to do this in a web-based application running PHP.
I've tried DPZFlickr, which returns this, when trying to upload:
Array ( [stat] => fail [err] => Array ( ) )
Inspecting the Flickr API's response, it's the same as what is returned when trying Dantsu's version of phpFlickr, which returns this:
oauth_problem=signature_invalid&debug_sbs=...
I've rolled my own CURL, which returns this:
Upload result: HTTP/1.1 200 OK Date: Wed, 23 Jan 2019 16:09:39 GMT Content-Type: text/xml; charset=utf-8 Content-Length: 109 P3P: policyref="https://policies.yahoo.com/w3c/p3p.xml", CP="CAO...
Here's the full code I use for creating my CURL request (edited to use CurlFile):
$consumerSecret = $flickrApiSecret;
$ap_url = "https://up.flickr.com/services/upload/";
$apiKey = $flickrApiKey;
$oauth_nonce = time();
$oauthToken = $_SESSION["FlickrSessionOauthData"]["oauth_request_token"];
$oauthTokenSecret = $_SESSION["FlickrSessionOauthData"]["oauth_request_token_secret"];
$text = "Test";
$signatureMethod = "HMAC-SHA1";
$oauthVersion = "1.0";
$timestamp = time();
$parms = "description=".$text."&format=json&oauth_consumer_key=".$apiKey."&oauth_nonce=".$oauth_nonce;
$parms .= "&oauth_signature_method=".$signatureMethod."&oauth_timestamp=".$timestamp."&oauth_token=".$oauthToken;
$parms .= "&oauth_version=".$oauthVersion."&title=".$text;
$baseString = "";
$baseString .= "POST&".urlencode($ap_url)."&".urlencode($parms);
$hashkey = $consumerSecret."&".$oauthTokenSecret;
$apiSignature = base64_encode(hash_hmac('sha1', $baseString, $hashkey, true));
$filePath = "/path_to_file/0.jpg";
$postFields["description"] = $text;
$postFields["format"] = "json";
$postFields["photo"] = new \CurlFile($filePath, mime_content_type ( $filePath ), 'photo');
$postFields["title"] = $text;
print_r ($postFields);
print "<br />";
$url = "https://up.flickr.com/services/upload/";
$oauth_header = "oauth_consumer_key=".$apiKey.",oauth_nonce=".$oauth_nonce.",oauth_signature_method=".$signatureMethod.",oauth_timestamp=".$timestamp.",oauth_token=".$oauthToken.",oauth_version=".$oauthVersion.",oauth_signature=".$apiSignature;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: OAuth ".$oauth_header));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_VERBOSE, 0);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
$response = curl_exec ($curl);
curl_close ($curl);
echo $response;
I'm at a loss. How to make this work?
This question and answer got me going in the right direction.
I still was unable to get my own CURL up and running, but I managed to hack a few lines of code in DPZFlickr's library to get that working.
I updated the httprequest function to this:
private function httpRequest($url, $parameters)
{
if (isset($parameters["photo"])) {
$p = $parameters["photo"];
$pf = substr($p, 1);
$parameters["photo"] = new \CurlFile($pf, mime_content_type ( $pf ), 'photo');
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_TIMEOUT, $this->httpTimeout);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
if ($this->method == 'POST')
{
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $parameters);
}
else
{
// Assume GET
curl_setopt($curl, CURLOPT_URL, "$url?" . $this->joinParameters($parameters));
}
$response = curl_exec($curl);
$headers = curl_getinfo($curl);
curl_close($curl);
$this->lastHttpResponseCode = $headers['http_code'];
return $response;
}
This includes one change:
Changing how the photo is included. Now through CurlFile.
I'm doing this on PHP 7.2. Apparently, the CURLOPT_SAFE_UPLOAD underwent some changes in PHP 5.x, while CurlFile became a requirement in PHP 7.1.
Related
Can someone help me to fix this issue, i need to provide an object type parameter to my code to fetch data using shopee API.
here is my code
$partner_key = "c423d22ccf4a8f1ca3cf9f49d7995f7d2a11e58b6a57036bd8385e8d978b4db2";
$partner_id = 2003151;
$shop_id = 30334567;
$ordersn = "";
$username = "info#pollandhopia.com";
$password = "101382qpqeiw";
$datenow = time();
$parcel->item_id = 455371271;
$parcel->variation_id = 0;
$parcel->order_item_id = 455371271;
$parcel->promotion_group_id = 0;
$object = json_encode($parcel);
$post = '{
"shopid": '.$shop_id.',
"ordersn": "220506EWDX3UXW",
"partner_id": '.$partner_id.',
"timestamp": '.$datenow.',
"parcels": '.$parcel.'
}';
$url = "https://partner.shopeemobile.com/api/v1/orders/split";
//Generate a signature base string for POST
$base_string = $url."|".$post;
//Generate a unique signature
$signature = hash_hmac('sha256', $base_string, $partner_key);
#echo $signature.'----'.$datenow.'-'.$object;exit;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization:".$signature, "Content-Type: application/json"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$result = json_decode($result);
curl_close($ch);
Then the documentation params is here
Here is my error:
An uncaught Exception was encountered
Type: Error
Message: Object of class stdClass could not be converted to string
Our team is working on developing a web application for accessing a 3D printer remotely in PHP. We tried implementing the POST print_job part using the multipart/form-data but it doesn't work, which shows no file received. This API would check id and key. Here is the code. Any help is appreciated!
It's running on Apache 2.4.39, PHP 7.3.5, XAMPP Control Panel 3.2.2.
The details are:
<?php
function callAPI($method, $url, $data){
$curl = curl_init();
switch ($method){
case "POST":
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
$username = "";
$password = "";
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 90);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// EXECUTE:
$result = curl_exec($curl);
if(!$result){die("Connection Failure");}
curl_close($curl);
return $result;
}
?>
<?php
include('api.php');
$_SESSION['ip'] = "";
$_SESSION['url'] = "http://".$_SESSION['ip']."/api/v1";
$target_dir = "../uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
$filedata = $_FILES["file"]["tmp_name"];
echo $target_file;
$data_array = array(
"jobname" => "file",
"file" => "new \CURLFile(realpath($filedata))"
);
$_SESSION['size'] = $_FILES['file']['size'];
//$make_call = callAPI('POST', $_SESSION['url']."/print_job", $data_array);
$response = callAPI('POST', $_SESSION['url']."/print_job", $data_array);
$_SESSION['print'] = $response;
header('location: ../index.php');
?>
Ps: If I want to upload the file which was got from front-end to the remote API, I may have to store it locally. Then I tried it as the following code. It works.
file_put_contents("E:/xyz/test.gcode",file_get_contents("../uploads/".$_FILES["file"]["name"]));
$filedata='E:/xyz/test.gcode';
if(!is_readable(realpath($filedata))){throw new \RuntimeException("upload file not readable!");}
$data_array = array(
'jobname' => 'file',
'file' => new \CURLFile($filedata)
);
first off, don't set the Content-Type:multipart/form-data header manually because you'll corrupt the boundary if you do. the full header looks something like:
Content-Type: multipart/form-data; boundary=------------------------777d48028c332f50
so remove this:
$headers = array("Content-Type:multipart/form-data");
and let curl set it for you. (curl will automatically set that header, with the correct boundary, when setting CURLOPT_POSTFIELDS to array.)
second, you're not sending an actual file here, you're just sending the literal string
new \CURLFile(realpath($filedata))
.. if you want to send the file pointed to by $filedata , do
$data_array = array(
"jobname" => "test",
"file" => new \CURLFile(realpath($filedata))
);
instead.
I am struggling using Binance's REST API. I have managed to get working GET request via query string such as pinging the server, ticker information, etc. My challenge now is performing POST request via query string using cURL. I have been scraping code from various places and referring back to the API to get pieces to work but I am unsure as to why I am getting this error returned from the result... {"code":-1102,"msg":"Mandatory parameter 'signature' was not sent, was empty/null, or malformed."}
(ERROR SHOWN ON WEBPAGE). I echo out the signature and its a load of gibberish so I would believe that the hash_hmac performed at the top would be working, but honestly I got pretty lucky making the GET request work. Does anyone have any suggestions as to why this would be broken? Thanks!
$apikey = "MYKEY";
$apisecret = "MYSECRET";
$timestamp = time()*1000; //get current timestamp in milliseconds
$signature = hash_hmac('sha256', "TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000×tamp=".$timestamp, $apisecret);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.binance.com/api/v3/order/test");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, "symbol=TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000×tamp=".$timestamp);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$apikey,"signature: ".$signature));
$response = curl_exec($ch);
curl_close($ch);
echo $response;
As per their API docs:
SIGNED endpoints require an additional parameter, signature, to be sent in the query string or request body.
You are sending the signature via neither of these methods and are instead sending it through the header.
Change this:
curl_setopt($ch, CURLOPT_POSTFIELDS, "symbol=TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000×tamp=".$timestamp);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$apikey,"signature: ".$signature));
To this:
curl_setopt($ch, CURLOPT_POSTFIELDS, "symbol=TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000×tamp=" . $timestamp . "&signature=" . $signature);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$apikey));
<?php
$secret = "F................";
$key = "D.................";
$s_time = "timestamp=".time()*1000;
$sign=hash_hmac('SHA256', $s_time, $secret);
$url = "https://api.binance.com/api/v3/account?".$s_time.'&signature='.$sign;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-MBX-APIKEY:'.$key));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
$result = json_decode($result, true);
echo '<pre>';
var_dump($result);
echo '</pre>';
?>
Here is an example, using php-curl-class
// Variables
// url, key and secret is on separate file, called using require once
$endPoint = "/api/v3/order/test";
$coin = "BTC";
$fiat = "EUR";
$symbol = $coin . "" . $fiat;
$side = "BUY";
$type = "LIMIT";
$timeInForce = "GTC";
$quantity = 1;
$price = 10000;
$timestamp = time();
// Constructing query arrays
queryArray = array(
"symbol" => $symbol,
"side" => $side,
"type" => $type,
"timeInForce" => $timeInForce,
"quantity" => $quantity,
"price" => $price,
"timestamp" => $timestamp*1000
);
$signature = hash_hmac("sha256", http_build_query($queryArray), $secret);
$signatureArray = array("signature" => $signature);
$curlArray = $queryArray + $signatureArray;
// Curl : setting header and POST
$curl->setHeader("Content-Type","application/x-www-form-urlencoded");
$curl->setHeader("X-MBX-APIKEY",$key);
$curl->post($url . "" . $endPoint, $curlArray);
if ($curl->error) {
echo 'Error: ' . $curl->errorCode . ': ' . $curl->errorMessage . "\n";
}
$order = $curl->response;
print_r($order);
I had the same problem, and nothing of above doesn't helped.
So I finaly figured out how to make order on my way.
So, maybe this helps someone.
function Kupovina($buy_parametri) {
$key = "xxxxxxxxxxxxxxx";
$secret = "xxxxxxxxxxxx";
$s_time = "timestamp=".time()*1000;
$timestamp = time()*1000; //get current timestamp in milliseconds
$sign = hash_hmac('sha256', $buy_parametri."×tamp=".$timestamp, $secret);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.binance.com/api/v3/order");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $buy_parametri."&".$s_time."&signature=".$sign);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$key));
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$buy_parametri = "symbol=BTCUSDT&type=market&side=buy&quantity=0.00086";
Call function:
Kupovina($buy_parametri);
I am trying to call changelly API with below codes but it is returning "Unauthorized" in response.
Appreciate if someone can help in identifying the mistake I am making in below code.
$API_URL = 'https://api.changelly.com';
$API_KEY = 'XXXXX';
$API_SECRET = 'XXXXX';
$message = array();
$message['jsonrpc'] = '2.0';
$message['method'] = 'getMinAmount';
$message['params'] = array('from' => 'BTC', 'to' => 'LTC');
$message['id'] ='12345';
$data = json_encode($message);
$sign = hash_hmac('SHA512', $data, $API_SECRET);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_URL);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_GET, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Accept: application/json",'Authorization:api-key: '.$API_KEY.':sign: '.$sign));
$final_result = curl_exec($ch);
curl_close($ch);
echo '<pre>';
print_r($final_result);
Changelly API guide is at https://changelly.com/developers
Thanks
in your code you have wrong set of headers.
please check this example: https://github.com/changelly/changelly-examples/blob/master/php/example.php, hope it helps.
I want to get html of a URL. Basically I am doing this :
$client = new Zend_Http_Client($url);
$client->setConfig(array('strictredirects' => true, 'timeout'=> 100, 'storeresponse' => true));
$response = $client->request();
$html = $response->getBody();
For some urls that redirect, i am getting the following error
Invalid URI supplied
For example if you consider the following URL:
http://www.hiexpress.com/redirect?path=hd&brandCode=ex&hotelCode=housl®ionCode=1&localeCode=en&cm_mmc=mdpr--GoogleMaps--ex-_-housl
It redirects to another URL. When i try to get the lastResponse, it gives me nothing. HOw do i get the html for this URL??
I tried the config option strictredirects but still its giving the same error. HOw do i solve this??
Try this put this into your controller
// #$uri your url
$client = new Zend_Http_Client($uri, array(
'maxredirects' => 2,
'timeout' => 10,
));
// Try to mimic the requesting user's UA
$client->setHeaders(array(
'User-Agent' => $_SERVER['HTTP_USER_AGENT'],
'X-Powered-By' => 'Zend Framework'
));
$response = $client->request();
$body = $response->getBody();
$body = trim($body);
// Get DOM
if( class_exists('DOMDocument') ) {
$dom = new Zend_Dom_Query($body);
} else {
$dom = null; // Maybe add b/c later
}
$title = null;
if( $dom ) {
$titleList = $dom->query('title');
if( count($titleList) > 0 ) {
$title = trim($titleList->current()->textContent);
$title = substr($title, 0, 255);
}
}
$this->view->title = $title;//Title of the page
$description = null;
if( $dom ) {
$descriptionList = $dom->queryXpath("//meta[#name='description']");
// Why are they using caps? -_-
if( count($descriptionList) == 0 ) {
$descriptionList = $dom->queryXpath("//meta[#name='Description']");
}
if( count($descriptionList) > 0 ) {
$description = trim($descriptionList->current()->getAttribute('content'));
$description = substr($description, 0, 255);
}
}
$this->view->description = $description;// Description of the page
For some reason Zend Http Client did not work, had to use CURL to get the work done.
To get HTML :
$headers = array( "User-Agent:MyAgent/1.0\r\n");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_MAXREDIRS, 50);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_TIMEOUT, 20);
$html = curl_exec($curl);
curl_close($curl);
echo $html;
To get the Effective Url / redirected url :
$headers = array( "User-Agent:MyAgent/1.0\r\n");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_MAXREDIRS, 50);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curl, CURLOPT_TIMEOUT, 20);
$content = curl_exec($curl);
$redirectedUrl = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
curl_close($curl);
echo $redirectedUrl;