How do I use arrays in cURL POST requests with PHP - php

I am wondering how do I make this code support arrays?
i'am trying to send parameters via php curl in a stock screener to have the result in this page:
https://finance.yahoo.com/screener/unsaved/f0171a68-053e-42f2-a941-d6ecdf2ba6d1?offset=25&count=25
parameters
here is my php code
<?php
$url = 'https://query1.finance.yahoo.com/v1/finance/screener?lang=en-US&region=US&formatted=true&corsDomain=finance.yahoo.com';
// $url = 'https://finance.yahoo.com/screener/unsaved/f0171a68-053e-42f2-a941-d6ecdf2ba6d1';
$parameters =
[
'size' => 25,
'offset' => 50,
'sortField' => 'intradaymarketcap',
'sortType' => 'DESC',
'quoteType' => 'EQUITY',
'topOperator' => 'AND',
'query' => array(
'operator' => 'AND',
'operands'=> array(
'operator' => 'or',
'operands' => array(
'operator' => 'EQ',
'operands' => array("region","jp")
)
)
),
'userId' => 'HFEELK3VBE3KPE4MGEA6PZTXXL',
'userIdType' => 'guid'
];
$parameters = json_encode($parameters);
$headers =
[
'Accept: application/json, text/javascript, */*; q=0.01',
'Accept-Language: en-US,en;q=0.5',
'X-Requested-With: XMLHttpRequest',
'Connection: keep-alive',
'Pragma: no-cache',
'Cache-Control: no-cache',
];
$cookie = tmpfile();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.31');
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters));
// curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
?>

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters));
Change this line. If your problem is that you can send the body through curl then probably you need to send it as a json so try
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($parameters,true));
I saw your comment that you tried to send it already as array and i assume it did not work so i am almost sure that in your post you need to send a json (which is the most common body format for post requests)

Working Example
$data=array();
$data['amount']=100;
$data['to']='test';
$json=json_encode($data);
$header = array('Content-Type: application/json');
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($handle, CURLOPT_POSTFIELDS, $json);
curl_setopt($handle, CURLOPT_HTTPHEADER, $header);
$response=curl_exec($handle);

thank you pr1nc3 and Gurpal singh
i changed this line
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters));
for this one
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($parameters,true));
but i always have this result
'{"error":{"result":null,"error":{"code":"internal-error","description":"STREAMED"}}}'
here again the code
<?php
$url = 'https://query1.finance.yahoo.com/v1/finance/screener?lang=en-US&region=US&formatted=true&corsDomain=finance.yahoo.com';
// $url = 'https://finance.yahoo.com/screener/unsaved/f0171a68-053e-42f2-a941-d6ecdf2ba6d1';
$parameters =
[
'size' => 25,
'offset' => 50,
'sortField' => 'intradaymarketcap',
'sortType' => 'DESC',
'quoteType' => 'EQUITY',
'topOperator' => 'AND',
'query' => array(
'operator' => 'AND',
'operands'=> array(
'operator' => 'or',
'operands' => array(
'operator' => 'EQ',
'operands' => array("region","jp")
)
)
),
'userId' => 'HFEELK3VBE3KPE4MGEA6PZTXXL',
'userIdType' => 'guid'
];
$headers =
[
'Accept: application/json, text/javascript, */*; q=0.01',
'Accept-Language: en-US,en;q=0.5',
'X-Requested-With: XMLHttpRequest',
'Connection: keep-alive',
'Pragma: no-cache',
'Cache-Control: no-cache',
];
$cookie = tmpfile();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.31');
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($parameters,true));
// curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
?>
i think the error is in the variable $parameters but i don't see where
when i compare view source send
{"size":25,"offset":0,"sortField":"intradaymarketcap","sortType":"DESC","quoteType":"EQUITY","topOperator":"AND","query":{"operator":"AND","operands":[{"operator":"or","operands":[{"operator":"EQ","operands":["region","jp"]}]}]},"userId":"HFEELK3VBE3KPE4MGEA6PZTXXL","userIdType":"guid"}
with my variable $parameters, there are diferences
{"size":25,"offset":0,"sortField":"intradaymarketcap","sortType":"DESC","quoteType":"EQUITY","topOperator":"AND","query":{"operator":"AND","operands":{"operator":"or","operands":{"operator":"EQ","operands":["region","jp"]}}},"userId":"HFEELK3VBE3KPE4MGEA6PZTXXL","userIdType":"guid"}

Related

POSTing "/orders" to the GDAX API fails silently

I am trying to POST "/orders" to GDAX using a simple PHP function. I am getting no response and no errors. Orders are not getting placed and there are no PHP errors/warnings.
Not sure where I am going wrong.
function gdaxPost ($path, $post_array){
$url = 'https://api-public.sandbox.gdax.com/'.$path;
// Sandbox API #1 - fake key
$key = "03cc35bd4fb48ardad8097e0a45f";
$secret = "ihGzWV+li8AweKcL+oMDUvBzlmq9fR7z6rKksg43VFcWA3zysg6TxM+gGhEn0wg==";
$passphrase = "jqer9jxgfa6qcl";
$time = time();
$data = $time."POST"."/orders";
$sign = base64_encode(hash_hmac("sha256", $data, base64_decode($secret), true));
$headers = array(
'CB-ACCESS-KEY: '.$key,
'CB-ACCESS-SIGN: '.$sign,
'CB-ACCESS-TIMESTAMP: '.$time,
'CB-ACCESS-PASSPHRASE: '.$passphrase,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_array));
curl_setopt($ch, CURLOPT_URL, $url);
$res = curl_exec($ch);
return $res;
}
$path = 'orders';
$post_array = array(
"price" => "600",
"size" => "1.01",
"side" => "buy",
"type" => 'limit',
"time_in_force" => "GTC",
"product_id" => "BTC-USD"
);
print_r(json_decode(gdaxPost ($path, $post_array)),true);
EDIT: I fixed the code!
This is the updated working code:
function gdaxPost ($path, $post_array){
$url = 'https://api-public.sandbox.gdax.com/'.$path;
// Sandbox API #1 - fake key
$key = "03cc35bd4fb48ardad8097e0a45f";
$secret = "ihGzWV+li8AweKcL+oMDUvBzlmq9fR7z6rKksg43VFcWA3zysg6TxM+gGhEn0wg==";
$passphrase = "jqer9jxgfa6qcl";
$time = time();
$data = $time."POST"."/".$path.json_encode($post_array);
$sign = base64_encode(hash_hmac("sha256", $data, base64_decode($secret), true));
$headers = array(
'CB-ACCESS-KEY: '.$key,
'CB-ACCESS-SIGN: '.$sign,
'CB-ACCESS-TIMESTAMP: '.$time,
'CB-ACCESS-PASSPHRASE: '.$passphrase,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_array));
curl_setopt($ch, CURLOPT_URL, $url);
$res = curl_exec($ch);
return $res;
}
$path = 'orders';
$post_array = array(
"price" => "600",
"size" => "1.01",
"side" => "buy",
"type" => 'limit',
"time_in_force" => "GTC",
"product_id" => "BTC-USD"
);
print_r(gdaxPost ($path, $post_array));

Curl request works on console but not in PHP

This simple request works on my console
curl 'https://www.nike.com/en'
But in PHP (with or without options like headers, useragent ...) I get Access Denied 403
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.nike.com/en");
$result = curl_exec($ch);
Thanks
Well, this would work for you.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.nike.com/en");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 40000);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
echo $result;
<?php
class Curl {
public static function makeRequest($url) {
$ch = curl_init();
$request_headers = [
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8;',
'Accept-Encoding: gzip, deflate',
"Connection: keep-alive",
"Content-Type: text/html; charset=UTF-8",
];
$options = [
CURLOPT_URL => $url,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_USERAGENT => "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0",
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_AUTOREFERER => true,
CURLOPT_COOKIESESSION => true,
CURLOPT_FILETIME => true,
CURLOPT_FRESH_CONNECT => true,
CURLOPT_HTTPHEADER => $request_headers,
CURLOPT_COOKIESESSION => true,
CURLOPT_ENCODING => "gzip, deflate, scdh",
];
curl_setopt_array($ch, $options);
$result['content'] = curl_exec($ch);
$result['header'] = curl_getinfo($ch);
$result['error'] = curl_error($ch);
return $result;
}
}
var_dump(Curl::makeRequest('https://www.nike.com/en')['header']);
Some website strictly check the request headers and return you encoded so .. I added request headers ad decoding method to decode the content

Error code 410 when polling Skyscanner flight live prices

I am polling live prices from the Skyscanner API. Although I receive the session_key and although I am immediately polling the results I am getting a 410 (Gone) response header with an empty body. It used to work fine from my localhost environment but not on my live server anymore.
Has anybody experienced this before and can maybe give me a hint what the issue could be?
$url_api = "http://partners.api.skyscanner.net/apiservices/pricing/v1.0/";
$api_key = "XXX"; // Not shown here
$data = array('apiKey' => $api_key, 'country' => 'DE', 'currency' => 'EUR',
'locale' => 'de-DE', 'originplace' => 'HAM', 'destinationplace' => 'AMS', 'cabinclass' => 'economy', 'outbounddate' => '2017-01-27',
'inbounddate' => '2017-01-30' , 'locationschema' => 'Iata', 'groupPricing' => true);
$httpdata = http_build_query($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_api);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $httpdata);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded', 'Accept: application/json'));
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
$response = curl_exec($ch);
curl_close($ch);
$headers = get_headers_from_curl_response($response);
$url = $headers['Location']."?apiKey=".$api_key."&stops=0";
echo $url;
return;

SkyScanner API error when called by PHP

I did exactly as shown in the API documentation
http://business.skyscanner.net/portal/en-GB/Documentation/FlightsLivePricingList
but when i call it returns this error
HTTP/1.1 100 Continue HTTP/1.1 500 Internal Server Error Cache-Control: private Content-Type: application/json Date: Sat, 04 Jun 2016 06:23:48 GMT Connection: close Content-Length: 2 {}
and here is my code in PHP
<?
$url = 'http://partners.api.skyscanner.net/apiservices/pricing/v1.0/';
$data = array('apiKey' => 'de995438234178656329029769192274', 'country' => 'BR', 'currency' => 'BRL',
'locale' => 'pt-BR', 'originplace' => 'SDU-iata', 'destinationplace' => 'GRU-iata', 'outbounddate' => '2016-09-23',
$headers = 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded', 'Accept: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
printf($result);
?>
any idea what is going wrong?
thanks in advance for any kind
So I think the PHP is sending the wrong request type, because the HTTP headers were being sent as an array (so defaults to 'multipart/formdata'). If you use http_build_query on that array, it is sent correctly as 'x-www-form-urlencoded'.
I've tidied things up, removed some duplication in the curl options, and correctly get a 201 response on your example now:
<?
$url = 'http://partners.api.skyscanner.net/apiservices/pricing/v1.0/';
$data = array('apiKey' => 'de995438234178656329029769192274', 'country' => 'BR', 'currency' => 'BRL',
'locale' => 'pt-BR', 'originplace' => 'SDU', 'destinationplace' => 'GRU', 'outbounddate' => '2016-09-23', 'locationschema' => 'Iata', 'adults' => 1);
$httpdata = http_build_query($data);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $httpdata);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded', 'Accept: application/json'));
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
?>
Hope that helps, I'll keep an eye on the thread in case of anything else - feel free to drop us a query or check the FAQs here: https://support.business.skyscanner.net/hc/en-us

Invalid json response on remote server

I have a very strange problem which I have been trying to figure out for 2 days, I have the below code to fetch information from a site for flight information, it works perfectly on my localhost and returns me "{thedata:what_I_Need}" but when I upload the script on my server it returns an "{invalid:true}" error from the site.
I tried it on 4 different droplets/vps, each in a different country IP with the same configuration (same curl-php-apache version and modules) as my local computer ( using ubuntu 14.4 with php5) but it still has the same issue. Here is the code which works perfectly on localhost:
$url = 'http://site.url.com';
$post = array(
'LanguageID' => 2,
'Trips' => array(array(
'Origin' => "JFK",
'Destination' => "TEX",
'Departure' => "2015-12-24T00:00:00",
)),
'Return' => "2015-12-28T00:00:00",
'Carriers' => null
'Adults' => 1,
'Children' => 0
);
$data_string = json_encode($post);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
curl_setopt($ch,CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1");
curl_setopt($ch, CURLOPT_REFERER, "http://www.site.url.com");
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'X-Requested-With: XMLHttpRequest',
'Content-Length: ' . strlen($data_string))
);
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
$output=curl_exec($ch);
curl_close($ch);
I followed this article as well but I still have same issue on the remote site even if I replace CURLOPT_POST with
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

Categories