curl to php conversion, array + json - php

I have this curl code i need to convert it to php
curl -H "Content-Type: application/json" -d '{"command":"sendoffer",
"steamID":"###############","token":"lkTR4VG2", "itemIDsToRequest":["4942877123","4892501549"],
"message": "Message"}' http://website:1337/
As you can see there is an array along with normal json.
"itemIDsToRequest":["4942877123","4892501549"]
I looked at many question like this and this, but couldn't understand how to implement it.
Im sorry im very new to curl command.

the array is part of a JSON string that is not interpreted but used as plain string data in CURL so it does not really matter what is in there; use the very same JSON string as from your commandline example, so:
$data = '{"command":"sendoffer", "steamID":"###############","token":"lkTR4VG2", "itemIDsToRequest":["4942877123","4892501549"], "message": "Message"}'
curl_setopt($ch, CURLOPT_POSTFIELDS, $data );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

If your array is
$data = array("command"=>"sendoffer", "steamID"=>"###############","token"=>"lkTR4VG2", "itemIDsToRequest"=>array("4942877123","4892501549"),"message"=>"Message");
Then send it on its way as json format with curl like that :
$url = 'http://website:1337/';
$ch = curl_init( $url );
// Convert array to json string
$data_json = json_encode( $data );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $data_json );
// Indicate in the header that it is json data
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
// Send request
$result = curl_exec($ch);
curl_close($ch);

Related

Sending jsonstring as body with cUrl in PHP

I am having some issues with cUrl and jsonstring.
I have a PHP script which receives a jsonstring that looks like this:
'{"CreateDateTime":"20220405T000000","ExternalID":"","HCP":"36000","PHCP":"3","Course":{"ExternalID":"7A263511-A3EB-453A-BEE9-F36ED812E51D","ClubID":"1B39F017-FC26-405C-BEC0-67AA40C9360F","Name":"Marion Golfclub","Country":"US","TeeID":"","TeeName":"Yellow","TeePar":"72","TeeRating":"712000","TeeSlope":"129"}}'
Now, when trying to run a cUrl like this:
$url = "https://my.api.io/some#mail.com/clubs/members/exchangedscorecards";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"Accept: application/json",
"Content-Type: application/json",
"Authorization: basic ahuYty5yTyuytgFLb1JBVEVycG9Daw=="
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$data = '{"CreateDateTime":"20220405T000000","ExternalID":"","HCP":"36000","PHCP":"3","Course":{"ExternalID":"7A263511-A3EB-453A-BEE9-F36ED812E51D","ClubID":"1B39F017-FC26-405C-BEC0-67AA40C9360F","Name":"Marion Golfclub","Country":"US","TeeID":"","TeeName":"Yellow","TeePar":"72","TeeRating":"712000","TeeSlope":"129"}}';
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($curl);
curl_close($curl);
echo $resp;
I get this error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Entities.ScorecardExchangeInput]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'CreateDateTime', line 1, position 18.
What am I doing wring, or what am I missing?
Really hoping for help and thanks in advance :-)

Pass Array to CURL - Read CSV file

My CSV has a single column with 40000 phone numbers
The following code read the CSV column and is fast
$dataArray = csvstring_to_array( file_get_contents('test.csv'));
My CURL code looks like this
$ch = curl_init();
$data = http_build_query($dataArray);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataArray);
curl_setopt($ch, CURLOPT_URL, "https://api.theblacklist.click/standard/api/v1/bulkLookup/key/[APIKEY]/response/json");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$output = curl_exec($ch);
The JSON parameters expected by the API look like the following. I am stuck about how to pass the "phones":[ and then pass the CSV Data array as a parameter to the curl/API?
curl -XGET ''
-H 'Content-Type: application/json'
-d'
{
"phones":[
"15555558353",
"15555555555",
"15555552740",
"15555552741",
"15555552738"
]
}'
It seems the API server expect JSON-formatted data to be passed as POST body
$dataArray = csvstring_to_array(file_get_contents('test.csv'));
$jsonString = json_encode(['phones' => array_values($dataArray)]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonString);

How to send HTML code with cURL?

am struggling with this for weeks now..
what is the correct way to send HTML-code with cURL ??
I tried base46_encode() and also json_encode() .. but on the reciever-side I always get a unuseable string.. how would i encode a html-code for sending?
$ch = curl_init($url);
$payload = json_encode( $data );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
curl_close($ch);
You can pass an array directly to cURL as documented on PHP.net, try turn the payload data into an array and send directly into cURL or via HTTP Build Query.
HTTP Build Query
Possible duplicate of:
PHP + curl, HTTP POST sample code?
and
Post HTML content via cURL

Not able to send json data through api [duplicate]

This question already has answers here:
How to POST JSON Data With PHP cURL?
(7 answers)
Closed 5 years ago.
I am using an external api where i have been given the following details related to that api
API KEY (Mandatory Header) :- apikey : "xxxxx"
Stage Server Base Url :- https://example.com
To add Details API :- POST(/student/{student_id})
What I plan to do is:
I would be collecting data from users through codeigniter form and
then will forward the data to the above api and get a response from
the api and accordingly if its a success then would perform furthur
actions or else need to display error message
However for testing purpose i am using a static array and trying to send it to the api.
What actually is happening is I am getting a blank result and so not sure if it is working or not.
Following is my code
<?php
$apiKey = 'xxxx';
$url = 'https://www.example.com';
$data = array("name"=> "ABC","location"=> "loc","class"=> 'tenth',"area"=> "area");
$ch = curl_init( $url );
$payload = json_encode( $data );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
$headers= curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','Authorization: ' . $apiKey));
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
curl_close($ch);
echo "<pre>$result</pre>";
?>
PS:I am new to api and curl so a little explanation along with the solution would be appreciated
$ch = curl_init('http://www.example.com');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json',
'Authorization:Basic '.$apikey,
)
);
$result = json_decode(curl_exec($ch));
try to add whether its Basic or Bearer in authorization header. Hope it works for you.
you should use like below statement
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));

Google Closure Compiler and multipart/form-data not working

I'm making a request to the google closure compiler API service:
$content = file_get_contents('file.js');
$url = 'http://closure-compiler.appspot.com/compile';
$post = true;
$postData = array('output_info' => 'compiled_code', 'output_format' => 'text', 'compilation_level' => 'SIMPLE_OPTIMIZATIONS', 'js_code' => urlencode($content)));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if ($post) {
curl_setopt($ch, CURLOPT_POST, $post);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded; charset=UTF-8'));
But the request is failing and I get this error message from google:
Error(18): Unknown parameter in Http request: '------------------------------0f1f2f05fb97
Content-Disposition: form-data; name'.
Error(13): No output information to produce, yet compilation was requested.
I looked at the headers and this Content-Type header is being sent:
application/x-www-form-urlencoded; charset=UTF-8; boundary=----------------------------0f1f2f05fb97
Not sure if that added boundary is normal? And how do I prevent this as google doesn't seem to like it?
Thank you,
Wesley
You have to use http_build_query() prior to sending POST data (array) to cURL.
string http_build_query ( mixed $query_data [, string $numeric_prefix [, string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] )
So your $postData should look like this:
$postData = http_build_query(
array(
'output_info' => 'compiled_code',
'output_format' => 'text',
'compilation_level' => 'SIMPLE_OPTIMIZATIONS',
'js_code' => urlencode($content)
)
);
Looks like Google's API doesn't support multipart/form-data data. Which seems a bit lame to me...
According to the PHP documentation on curl_setopt():
Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data,
while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.
So it should work if you change the 4th line of your code to something like this:
$postData = 'output_info=compiled_code&output_format=text&compilation_level=SIMPLE_OPTIMIZATIONS&js_code=' . urlencode($content);
In other words, you have to do the URL encoding yourself - you apparently can't rely on cURL to take an array and encode it for you.
1.) Don't use an array() to avoid switch to multipart/form-data:
Passing an array to CURLOPT_POSTFIELDS will encode the data as
multipart/form-data, while passing a URL-encoded string will encode
the data as application/x-www-form-urlencoded.
2.) Don't use http_build_query() to avoid double encoding problems (#Wesley). In addition you aren't able to use keys twice (I know this workaround, but its ugly).
Some of my error messages by using http_build_query():
JSC_PARSE_ERROR Input_0
Parse error. illegal octal literal digit 9; interpreting it as a decimal digit
Parse error. syntax error
ERROR - Parse error. missing ( before function parameters
3.) My proposal:
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Expect:',
'Content-type: application/x-www-form-urlencoded',
));
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // don't set it to low! sending and response needs time
curl_setopt($ch, CURLOPT_ENCODING, ''); // automatically sets supported encodings
//curl_setopt($ch, CURLOPT_HEADER, true); // for debugging response header
//curl_setopt($ch, CURLINFO_HEADER_OUT, true); // for debugging request header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // false would echo the answer
curl_setopt($ch, CURLOPT_POST, true);
// settings
curl_setopt($ch, CURLOPT_POSTFIELDS,
'output_format=json'
.'&output_info=compiled_code'
.'&output_info=warnings'
.'&output_info=errors'
.'&output_info=statistics'
.'&compilation_level=ADVANCED_OPTIMIZATIONS'
.'&warning_level=verbose'
//.'&output_file_name=default.js'
//.'&code_url='
.'&js_code=' . urlencode($js_code)
);
curl_setopt($ch, CURLOPT_URL, 'http://closure-compiler.appspot.com/compile');
$response = curl_exec($ch);
//$response = curl_getinfo($ch, CURLINFO_HEADER_OUT) . $response; // for debugging request header
print_r(json_decode($response, true));

Categories