Problem PHP with cURL - php

hi i have a problem with cURL and php. I use an API and i want to display only the results.
Here is my php + curl script
<?php
$file = "http://api.openkvk.nl/php/".rawurlencode("SELECT * FROM kvk WHERE kvks='20147376'");
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, $file);
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
?>
and the result what i get is this:
array(
array("RESULT" => array(
"TYPES"=>
array(
"int", "bigint", "varchar", "varchar", "varchar", "varchar", "varchar", "int", "int", "smallint", "smallint", "int"
),
"HEADER"=>
array("id", "kvk", "bedrijfsnaam", "adres", "postcode", "plaats", "type", "kvks", "sub", "bedrijfsnaam_size", "adres_size", "verhuisd"),
"ROWS"=>
array(
array("1008714", "20147376", "Stichting OpenGeo", "Spinellihof 44", "4463GP", "Goes", "Rechtspersoon", "20147376", NULL, "17", "14", "0")
)
)));

Your script outputs data, instead of returning it. Add this line:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
And then assign curl_exec to some variable:
$result = curl_exec($ch);
It seems that API returns some META information, such as field types. If you don't need it, the just work with 'ROWS' element
print_r($result['ROWS']);
It will look like this:
array(
"1008714","20147376","Stichting OpenGeo","Spinellihof 44","4463GP","Goes","Rechtspersoon","20147376",NULL,"17","14","0"
)
You can iterate through it:
for($i=0; $i<count($result['ROWS']); $i++)
{
echo $result['HEADER'][$i].': '.$result['ROWS'][$i].'<br />';
}

Related

Binance 400 response and duplicate values for a parameter detected

still trying to get my head around API's and connections.
I am trying to do a buy order to Binance but keep getting a 400 response. I know it's been an issue for some others but I just can't seem to suss out where I am going wrong. So hoping someone can help me out.
It's only issues with POST's, all the GET requests are working fine, and so to the signature and timestamp... or at least I am getting responses for my account so I assume so.
The first CURL is just for the serverTime, but the second CURL is for a buy/sell order.
This is the response I am getting now...
"Object ( [code] => -1102 [msg] => Mandatory parameter 'side' was not
sent, was empty/null, or malformed. )"
If I type the in the string manually it works just fine, but for one reason or another when I pass $qs it presents the above fault. I echoed $qs to the screen and copied that instead of passing $qs and it worked when I put in the new timestamp. I am stumped...
"symbol=TRXUSDC&side=SELL&type=LIMIT&timeInForce=GTC&quantity=63000.00000000&price=0.02550000&recvWindow=1000000&timestamp=1550922237310"
any advice?
$header = array('X-MBX-APIKEY:' . KEY);
$url = BINANCE . 'api/v1/time';
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl, CURLOPT_TIMEOUT, 60);
curl_setopt($curl, CURLOPT_ENCODING, "");
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl, CURLOPT_URL,$url);
$response = curl_exec($curl);
if (FALSE === $response){
echo curl_error($curl), curl_errno($curl);
}
$serverTime = json_decode($response);
curl_close($curl);
$url = BINANCE . "api/v3/order";
$signature = NULL;
$queryString = NULL;
$query = array(
"symbol" => "TRXUSDC",
"side" => "SELL",
"type" => "LIMIT",
"timeInForce" => "GTC",
"quantity" => number_format(63000.00000000,8,'.',''),
"price" => number_format(0.02550000,8,'.',''),
"recvWindow" => 1000000,
"timestamp" => $serverTime->serverTime);
$qs = htmlentities(http_build_query(array_unique($query)));
$query['signature'] = hash_hmac('SHA256', $qs, SECRET );
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl, CURLOPT_TIMEOUT, 60);
curl_setopt($curl, CURLOPT_ENCODING, "application/x-www-form-urlencoded");
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl,CURLOPT_FAILONERROR,FALSE);
curl_setopt($curl, CURLOPT_VERBOSE, TRUE);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS,$qs);
curl_setopt($curl, CURLOPT_URL, $url);
$response = curl_exec($curl);
if (FALSE === $response){
echo curl_error($curl).':'.curl_errno($curl);
}
$obj = json_decode($response);
curl_close($curl);
I tried this code and var_dump $qs
symbol=BTCUSDT&side=BUY&...
so I think you must remove amp;
Based on Binance spot api docs:
It is recommended to use a small recvWindow of 5000 or less! The max cannot go beyond 60,000!
so edit your query params with:
"symbol=TRXUSDC&side=SELL&type=LIMIT&timeInForce=GTC&quantity=63000.00000000&price=0.02550000&recvWindow=60000&timestamp=1550922237310"
Also you can check your other query params with exchange info that you can get with https://api.binance.com/api/v3/exchangeInfo that we have for your symbol:
{
"symbol": "TRXUSDC",
"status": "TRADING",
"baseAsset": "TRX",
"baseAssetPrecision": 8,
"quoteAsset": "USDC",
"quotePrecision": 8,
"quoteAssetPrecision": 8,
"baseCommissionPrecision": 8,
"quoteCommissionPrecision": 8,
"orderTypes": [
"LIMIT",
"LIMIT_MAKER",
"MARKET",
"STOP_LOSS_LIMIT",
"TAKE_PROFIT_LIMIT"
],
"icebergAllowed": true,
"ocoAllowed": true,
"quoteOrderQtyMarketAllowed": true,
"isSpotTradingAllowed": true,
"isMarginTradingAllowed": false,
"filters": [
{
"filterType": "PRICE_FILTER",
"minPrice": "0.00001000",
"maxPrice": "1000.00000000",
"tickSize": "0.00001000"
},
{
"filterType": "PERCENT_PRICE",
"multiplierUp": "5",
"multiplierDown": "0.2",
"avgPriceMins": 5
},
{
"filterType": "LOT_SIZE",
"minQty": "0.10000000",
"maxQty": "9000000.00000000",
"stepSize": "0.10000000"
},
{
"filterType": "MIN_NOTIONAL",
"minNotional": "10.00000000",
"applyToMarket": true,
"avgPriceMins": 5
},
{
"filterType": "ICEBERG_PARTS",
"limit": 10
},
{
"filterType": "MARKET_LOT_SIZE",
"minQty": "0.00000000",
"maxQty": "659177.02430556",
"stepSize": "0.00000000"
},
{
"filterType": "MAX_NUM_ORDERS",
"maxNumOrders": 200
},
{
"filterType": "MAX_NUM_ALGO_ORDERS",
"maxNumAlgoOrders": 5
}
],
"permissions": [
"SPOT"
]
}
for other possible reasons check spot api docs in the link https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md
I tested the code and saw a few glitches in it :
$qs = htmlentities(http_build_query(array_unique($query)));
gave me an error ({"code":-1102,"msg":"Mandatory parameter 'side' was not sent, was empty/null, or malformed."}), so i replaced it with:
$qs = http_build_query(array_unique($query));
After that you created your signature, but never added it to you request. So do the following :
$signature = hash_hmac('sha256', $qs, $apiSecret);
$qs .= "&signature=" . $signature;
Also update your 'recvWindow' to a max of 60000 (I suggest 50000 or less (see the answer of #Tofiq Samali)) and you are ready to go!

Make HTTP request in cURL in proper way

I am passing data in Curl as below, it seems I have done something wrong as it is not working.... please guide me how to make the request correctly.
Below is the full code:
<?php
$url = 'https://staging.logistics.com/v2/shipments/create';
$data = '
"request_id" : "10",
"value": "false"
';
$data_string = json_encode(array(
"customer" => $data
));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type:application/json'
));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Authorization: Basic ZcnM6ZHV55tbXlLZXk="
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
echo "$result";
?>
I got this HTTP error:
415 Problem accessing /v2/shipments/create. Reason: Unsupported Media
Type
The "Unsupported Media Type" error is because you are not sending valid JSON. Since you create $data as a string, and then json_encode() it, you end up with double-encoded data, which the server does not recognise. The code shown in the question will cause $data_string to be output as
{"customer":"\r\n\"request_id\" : \"10\",\r\n \"value\": \"false\"\r\n"}
A usable version of this would be
{"customer": { "request_id" : "10", "value": "false" } }
To get that, you'd write the code by making a PHP object / array, and then encoding that object:
$data = array("request_id" => "10", "value" => "false");
$data_string = json_encode(array(
"customer" => $data
));
Here's a demo showing the output of the code above.
You could also shorten that code to:
$data = array(
"customer" => array(
"request_id" => "10",
"value" => "false")
)
);
$data_string = json_encode($data);
Your mistake was to confuse the creation of the data in the PHP code with the encoding of it into the textual transmission format (JSON, in this case). Instead you need to create the data in PHP using a (nested) associative arrays and regular arrays in such a way that when you pass that to json_encode(), the output payload is in the correct format required by the API.
Try concatenating the token to the curl option like so
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: ' . $your_token));

Obtaining highcharts image URL from PHP

I need to get a highcharts image, and I found a code to resolve my problem, obtaining the name of the image via ajax, and then I paste before the url of the Highcharts API, and I can download the image in PHP, now, I want to do this process in PHP, since the name, until the download; I have this code to get the name of highcharts image:
var optionsStr = JSON.stringify({
"xAxis": {
"categories": [
"PRUEBA",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
]
},
"series": [
{
"data": [1, 3, 2, 4],
"type": "line"
},
{
"data": [5, 3, 4, 2],
"type": "line"
}
]
}),
exportUrl ='https://export.highcharts.com/';
dataString = encodeURI('async=true&type=image/jpeg&width=800&options=' + optionsStr);
$.ajax(
{
type: 'POST',
data: dataString,
url: exportUrl,
success: function(data)
{
console.log('get the file from relative url: ', data);
grafica=exportUrl+data;
},
error: function(err)
{
console.log('error', err.statusText)
}
});
I get the name of the graphic: charts/chart.9973ffbcf0d748d6aae04ef6ec01979c.jpeg
I want to know how get the same in PHP, I have this code:
$DataEncoded = json_encode(
array(
'xAxis'=>
array(
'categories'=> ['Ene','Feb', 'Mar', 'Abr']
),
'series'=>
array(
array(
'data'=>[1,2,3,4],
'type'=>'line'
),
array(
'data'=>[5,6,7,8],
'type'=>'line'
)
)
)
);
$DataExtra = 'async=true&type=image/jpeg&width=800&options=';
$dataString = urlencode('async=true&type=image/jpeg&width=800&options='.$DataEncoded);
$url ='https://export.highcharts.com/';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
$json=curl_exec($ch);
if(curl_errno($ch)){
echo "Entro al curl Error";
throw new Exception(curl_error($ch));
}
var_dump(json_decode($json));
curl_close($ch);
But I receive a fantastic: NULL. Someone made this before?
I tried making this process via Angular 5, but, I must to program a cron job to delegate the process, so, I decided to use PHP. I tried with file_get_contents() but the webservice give me: "No data chart found".
I suspect your issue is here:
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
I believe this is expecting a String or an Array.
This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, value must be an array if files are passed to this option with the # prefix. As of PHP 5.5.0, the # prefix is deprecated and files can be sent using CURLFile.
Consider trying the following:
$dataArray = array(
"async" => true,
"type" => "image/jpeg",
"width" => 800,
"options" => $DataEncoded
);
And...
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataArray);
Credit to #Patrick Q for catching the Encoding Type. You're not exactly sending it JSON encoded data, but Form data essentially.
I used the recommendations of Twisty and finally I obtain the name of the image, thank you so much.
$dataString = ('async=true&type=image/jpeg&width=800&options='.$DataEncoded);
$url ='https://export.highcharts.com/?';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$dataString);
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = "Accept: application/json";
$headers[] = "Content-Type: application/x-www-form-urlencoded";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);

PHP set multipart or form data

I am trying to work with a html file using the following but I am having an issue doing it with the PHP api. I already have the files ready on the server but I cannot figure out how to set the multipart/form data using the following code to do the conversion. Lets say I have a html file in the same folder how do I use it in the following code for conversion.
Code for conversion :
<?php
//set POST variables
$fields = array('from' => 'markdown',
'to' => 'pdf',
'input_files[]' => "#/".realpath('markdown.md').";type=text/x-markdown; charset=UTF-8"
);
//open connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //needed so that the $result=curl_exec() output is the file and isn't just true/false
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
?>
Since PHP 5.5, the # format for specifying a file path is no longer valid, and the value will be sent as a raw string. Instead try curl_file_create. Also, regardless of version, don't forget to set CURLOPT_POST variable to true as well. This code also assumes you have read access to the file being uploaded.
<?php
$url = 'http://c.docverter.com/convert';
$fields = [
'from' => 'markdown',
'to' => 'pdf',
'input_files[]' => (PHP_VERSION_ID < 50500) ? '#' . realpath('markdown.md') : curl_file_create('markdown.md')
];
$result_file = 'uploads/result.pdf';
//open connection
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $fields,
CURLOPT_RETURNTRANSFER => true
]);
$result = curl_exec($ch);
curl_close($ch);
file_put_contents($result_file, $result);

Posting a form with several form fields and file using PHP curl

I am trying to post a form with some text input fields to my api, I also want to upload a file to the server at the same time. I did some research and came up with the following code as per suggestions from various websites, but it does not seem to work.
First Approach:
$cfile = new CURLFile('/home/xyz/myimge.jpg', 'image/jpeg', 'mymage.jpg');
$params = array(
"userid_id" => "some id #",
"file" => $cfile,
"name" => "test_file",
"gallery" => "myalbum"
);
$uri = 'http://myserver.com/somedir/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$response_data = curl_exec($ch);
//var_dump(curl_getinfo($ch));
//var_dump($response_data);
curl_close( $ch );
unset( $ch );
Second Approach:
$cfile = new CURLFile('/home/xyz/myimge.jpg', 'image/jpeg', 'mymage.jpg');
$params = array(
"userid_id" => "some id #",
"name" => "test_file",
"gallery" => "myalbum"
);
$params = array('item' => http_build_query($params), 'file' => $cfile );
$uri = 'http://myserver.com/somedir/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_POST, true );
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$response_data = curl_exec($ch);
//var_dump(curl_getinfo($ch));
//var_dump($response_data);
curl_close( $ch );
unset( $ch );
As per documentation, passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data. and I should get my form fields as $_POST array and the uploaded file as $_FILES array. Using both of these approaches, I get all my form fields in my receiving php template as post variables, but I do not get the file.
When I check the ccurl_getinfo output for content_type, I see it is :
["content_type"]=>
string(9) "text/html"
and not "multipart/form-data" as suggested in the documentation. Setting the content_type explicitly as "multipart/form-data" using curl_setopt also does not have any effect.
Many forums suggest using '#'.$filename format for submitting the file, but this seems to be deprecated as per PHP documentation. I am on PHP 5.5, and suggested way of uploading the file is forming a CURLFile object, which is what I am doing here.
Can any one suggest what is wrong in the above code?
Seems your approach is perfect, but there is a silly mistake.
You can try by adding extra header information. Hope it will work.
$headers = array("Content-Type:multipart/form-data");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

Categories