How to pass array of arguments to cURL in command line? - php

I got desired response when i send cURL request from my PHP script.
My request is like this.
$data = array ("[product[name]]" => "nw",
"[product[handle]]" => 150,
"[product[interval_unit]]" => "day",
"[product[interval]]" => 1,
"[product[price_in_cents]]" => 0,
"[product[initial_charge_in_cents]]" => 14200,
"[product[return_url]]" =>"http://mytrial.com/office/selfie/themes/adcampaign/56cee935-185c-4dfs-asdfa-2b6b0ae84a4d",
"[product[return_params]]" => "id={subscription_id}&customer_id={customer_id})");
$url="http://mytrial.com/office/selfie/themes/adcampaign/346423/products.json";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, 'sdfkjas2kjsd:x');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$res = curl_exec($ch);
curl_close($ch);
It's working properly. I want to do the same request in command line.First i json encoded the array and i tried with this commands
curl -u sdfkjas2kjsd:x -H Accept:application/json -H Content-Type:application/json -x POST --data product[name]=nw&product[handle]=142&product[interval_unit]=day&product[interval]=1&product[price_in_cents]=0&product[initial_charge_in_cents]=14400&product[return_url]=http:\/\/54.145.218.63\/dev_lpad\/launchpad\/advertisers\/adcampaign\/56cee935-185c-4349-a8a1-2b6b0ae84a4d&product[return_params]={id={subscription_id}&customer_id={customer_id}} http://mytrial.com/office/selfie/themes/adcampaign/346423/products.json
Then i got the error.
Error: Unable to parse request body
Is there any way to solve this?
UPDATE : The URL provided here is a dummy value,Actually i am trying to connect with Chargify API (Recurring billing solution ).

It seems that your server does accept json payload post data. You probably forgot to json_decode your data, here is the fix:
curl -u sdfkjas2kjsd:x -H Accept:application/json -H Content-Type:application/json --data '{"product":{"name":"nw","handle":150,"interval_unit":"day","interval":1,"price_in_cents":0,"initial_charge_in_cents":14200,"return_url":"http:\/\/mytrial.com\/office\/selfie\/themes\/adcampaign\/56cee935-185c-4dfs-asdfa-2b6b0ae84a4d","return_params":"id={subscription_id}&customer_id={customer_id})"}}' http://mytrial.com/office/selfie/themes/adcampaign/346423/products.json
If i send it to my php script <?php var_dump(json_decode(file_get_contents('php://input'))); I see correct answer:
object(stdClass)#1 (1) {
["product"]=>
object(stdClass)#2 (8) {
["name"]=> string(2) "nw"
["handle"]=> int(150)
...

Finally I could solve this issue by splitting the array parameters. My cURL cummand is this.
curl -u sdfkjas2kjsd:x -d 'product[name]":nw' -d '[product[handle]]=161' -d '[product[interval_unit]]=day' -d '[product[interval]]=1' -d '[product[price_in_cents]]=0' -d '[product[initial_charge_in_cents]]=14200' -d '[product[return_url]]=http:\/\/mytrial.com\/office\/selfie\/themes\/adcampaign\/56cee935-185c-4dfs-asdfa-2b6b0ae84a4d' -d 'product[return_params]=id={subscription_id}&{customer_id={customerC_id}})' http://mytrial.com/office/selfie/themes/adcampaign/346423/products.json

I think you should put your data inside single quotes
curl ... --data 'some data here' ...
EDIT:
ON WINDOWS the proper way to pass array argument via cURL is shown below:
curl -X POST http://localhost:8080/uploadMultipleFiles -H "content-type: multipart/form-data" -F "files=#C:\Users\...\Desktop\filename1.txt,C:\Users\...\Desktop\filename2.txt,C:\Users\...\Desktop\filename3.txt,C:\Users\...\Desktop\filename4.txt
See the use of comma separated filenames where the server expect files to be an Array of Files.

Related

How to Convert Curl command to php for -i -t option

I would like to convert below curl command into php and i tried to convert from https://incarnate.github.io/curl-to-php/ but its not converting properly. How can i set <myobject> in php curl? that i am not getting. Can anyone help me in this?
curl -i -T <myobject> -X PUT -H "X-Auth-Token: <token>" <storage url>
Looks like you want to use curl to upload a file...
Example
// initialise the curl request
$request = curl_init('http://example.com/');
// send a file
curl_setopt($request, CURLOPT_POST, true);
curl_setopt(
$request,
CURLOPT_POSTFIELDS,
array(
'file' => '#' . realpath('example.txt')
));
// output the response
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($request);
// close the session
curl_close($request);

Translate command-line cURL to PHP

I have a working cURL request I want to translate to PHP code:
curl \
-X POST \
-u live_abcdefg: \
-d '{
"recipient": {
"address": "test1#test.com"
}
}' \
https://api.sendwithus.com/api/v1/drip_campaigns/abcdefgh/activate
Here is the PHP code I'm trying:
<?php
$theurl = "https://api.sendwithus.com/api/v1/drip_campaigns/abcdefgh/activate";
$ch = curl_init($theurl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); // -X
curl_setopt($ch, CURLOPT_POSTFIELDS, '{ "recipient": { "address": "test2#test.com" } }'); // -d
curl_setopt($ch, CURLOPT_PROXYUSERPWD, 'live_abcdefg:'); // -u
$response = curl_exec($ch);
var_dump($response); // prints bool(true)
?>
EDIT: Sendwithus (the app that I'm sending requests to) shows that the second request didn't come through (second recipient test2#test.com wasn't saved).
What am I doing wrong?
What can I change in the PHP code to start debugging this issue?

How can I recieve and treat data from a cURL call

I have to send a json response from a cURL call.
The user send me a "test" variable to file.php.
On my php file, I use this code
$arr = array($arr = array('test' => 'ok'));
echo json_encode($arr);
And this for the cURL call
curl --request POST http://www.domain.com/WS/file.php -d '{ "test" : "12341234123412342" }'
Here is the answer
[{"test":null}]
What's the good way to get de POST variable and treat it in my php file?
Thanks
EDIT
Just in case, the problem comes from the cURL call. Here's the correct syntax:
curl -H "Content-Type: application/json" -X POST -d "{\"test\":\"12341234123412342\"}" http://www.domain.com/WS/file.php
Ur question is kinda confusing :)
so ur User sends u a variable in file.php
and u have to curl with that variable ?
why not just
curl --request POST http://www.domain.com/WS/file.php -d '{ "test" : "$_POST['USER_INPUT_VALUE']" }'
or am i missing something ?
Thanks for your help.
You're right, it might be confusing. I have to add some new details and give a better example.
The user execute that script in a file test_curl.php:
// test_curl.php
$url = "http://www.domain.com/WS/file.php";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'test' => '12345'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$contents = curl_exec($ch);
echo $contents;
curl_close($ch);
Here's the file.php
// file.php
$arr = array($arr = array('test' => $_POST['test']));
echo json_encode($arr);
I recieve the POST variable and it works. Here's what $contents recieve in test_curl.php
{"test" => "12345"}
New fact, it works with test_curl.php. I've got the good answer but when do it in command line with that code...
curl --request POST http://www.domain.com/WS/file.php -d '{ "test" : "12345" }'
...I've got this answer:
[{"test":null}]
And finally, my question is why the response is null when I make my call in command line?
That won't work.
In your post data you are sending a json/application content type. Inside the server, you are expecting content from a variable called test, which should only exists in a normal form key valued body, which is not the case.
So, you need to json_decode directly the raw body of the post data content, then access the test key inside it, as such:
$raw_body = file_get_contents('php://input');
$json = json_decode($raw_body);
$arr = array($arr = array('test' => $json['test']);
echo json_encode($arr);

curl_exec for uploading files in box api using php fails

I am able to upload the file using curl on the terminal with the following:
curl https://upload.box.com/api/2.0/files/content \
> -H "Authorization: Bearer {access-code}" -X POST \
> -F attributes='{"name":"tested.png", "parent":{"id":"3804480350"}}' \
> -F file=#/Applications/MAMP/htdocs/BoxappTest/test.png
But when I try to do the same using PHP with the following code:
$filePath=realPath("./test.png");
$xmlfile = file_get_contents("codes.xml");
$codes_data = simplexml_load_string($xmlfile);
$access_token=$codes_data->access_code;
$destination_filename="tested.png";
$id="3804480350";
$ch= curl_init();
curl_reset($ch);
echo "Uploading file...",'<br>';
$post = '{"name":"'.$destination_filename.'", "parent":{"id":"'.$id.'"}}';
$postfields = Array("attributes"=>$post,"file" => "#".$filePath);
$headers= Array("Authorization: Bearer " . $access_token);
curl_setopt($ch, CURLOPT_URL, "https://upload.box.com/api/2.0/files/content");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$output=curl_exec($ch);
$info=curl_getinfo($ch);
curl_close($ch);
if(curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
}
foreach($info as $data => $part) {
echo $data."=".$part, '<br>';
}
echo "File uploaded...",'<br>';
var_dump($output);
It gives me the following output:
Uploading file...
content_type=text/html;charset=UTF-8
http_code=400
header_size=243
request_size=260
filetime=-1
ssl_verify_result=0
redirect_count=0
total_time=1.118914
namelookup_time=0.000738
connect_time=0.022878
pretransfer_time=0.100239
size_upload=335
size_download=0
speed_download=0
speed_upload=299
download_content_length=0
upload_content_length=335
starttransfer_time=1.10153
redirect_time=0
redirect_url=
primary_ip=74.112.185.182
certinfo=Array
primary_port=443
local_ip=10.0.0.188
local_port=50008
request_header=POST /api/2.0/files/content HTTP/1.1 Host: upload.box.com Accept: */* Authorization: Bearer {access-code} Content-Length: 335 Expect: 100-continue Content-Type: multipart/form-data; boundary=------------------------....
File uploaded...
string(0) ""
I have gone over various sites but none of them seem to be right for my problem. No matter what I do, the content_type stays 'text/html'. I have tried to set it in the header and the post fields. But both didn't work. I know I am getting the access codes properly and that they are valid. I am not sure about the curl options though. Setting CURLOPT_VERBOSE or checking for errors does not return anything either. While without the CURLOPT_RETURNTRANSFER option, curl_exec returns true. Can someone help me understand where I am making a mistake here?
I was not able to solve this problem using php itself but using shell_exec() to run the fully form curl command actually worked. So I have stuck to that implementation.
$cmd = "curl https://upload.box.com/api/2.0/files/content \
-H \"Authorization: Bearer $access_token\" -X POST \
-F attributes='{\"name\":\"$dest_name\",\"parent\": {\"id\":\"$parent_id\"}}' \
-F file=#\"$filePath\"";
$result=shell_exec($cmd);
return result;
I hope this helps somebody.
http_code=400 Bad Request.
Try to set your header enctype='multipart/form-data',as upload file use form.
CURLOPT_POST TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms.
more php.net

calling CURL with POST data and headers on command line

I am using RESTAPI to communicate php client with django server. I have posted json data. The php code is
$arr=array("username"=>"dtthtdas45",
"password"=>"123456",
"email"=>"ramg#ram.com",
"is_active"=>"1",
"is_staff"=>"1",
"is_superuser"=>"1",
"promo_code"=>"1212121",
"gender"=>"m",
"birth_year"=>"1991",
"zip"=>"77707",
"first_name"=>"john",
"last_name"=>"doe",
"current_state"=>"1"
);
echo $data_string= json_encode($arr);
$ch = curl_init('http://localhost:8000/api/ecp/user/?format=json');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
How can i call same URL using command line only?
I tried the folowing
curl -H 'Content-Type: application/json' -X POST -d '{"username": "dtthtdas45", "password": "123456","email":"email#email.com","is_active":"1","is_staff":"1","is_superuser",promo_code":"1212121","gender":"m","birth_year":"1991","zip":"77707","first_name":"john","last_name":"doe","current_state":"1"}' http://localhost:8000/api/ecp/user/?format=json
but no luck , it shows the folowing error
curl: (6) Couldn't resolve host 'application'
curl: (6) Couldn't resolve host 'dtthtdas45,'
curl: (6) Couldn't resolve host 'password:'
How can i call same URL using command line only?
I didn't write out all the data pairs, but the following should get you started. I suggest reading more on curl
curl -H 'Content-Type: application/json' -X POST -d '{"username": "dtthtdas45", "password": "123456"}' http://localhost:8000/api/ecp/user/?format=json
Note: Assuming you are doing this for more endpoints, you might want to check out a tool like resty.

Categories