cURL Post Data Not Sending - php

I am trying to send POST data via cURL however it is not sending the data, however when I send them as GET variables it is sending, does anyone know what the problem could be?
curl_setopt_array($ch, array(
CURLOPT_URL => "local.new.api.test.com/authenticate/"
));
$data = array(
'username' => 'test',
'password' => 'test'
);
$data_string = json_encode($data);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

CURLOPT_POSTFIELDS is not a json encoded string. It requires a query string (similar to the query string in the URL-s after the question mark).
This should work:
$data_string = http_build_query($data, '', '&');
Or you can let the cURL extension to do the dirty work and pass an array with key-value pairs as the value:
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
From PHP.net
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.

Related

Posting a nested array in PHP using cURL

I have some data I need to post to an endpoint which is a nested array like:
$contentPostData = array(
'contents' => array(
'name' => $comment_text,
'fingerprint' => $fingerprint,
'signers' => array(
$ownerAuthId
)
)
);
When I try:
json_encode($contentPostData);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
I get the error:
string(518) "{"timestamp":1578447151168,"message":"Can't read request","details":["JSON parse error: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException
How do I format the contentPostData so that it can be deserialized correctly?
You mention:
json_encode($contentPostData);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
But are you assigning the encoded json to $data? I mean:
are you doing:
$data = json_encode($contentPostData);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
I see that the webservice to which you are calling uses com.fasterxml.jackson so most likely expects JSON format and therefore your serialization should be okay (if field names and types match).
I also suggest setting the header to inform that webservice that you are sending a json file (in case it allows other formats):
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
);
So:
$data = json_encode($contentPostData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
If that does not work then most likely: a) your JSON is invalid (different structure is expected) or b) the webservice actually expects a different format than JSON (maybe standard multipart data for example)

Could not parse the 'params' argument as valid JSON (PHP, cURL, REST)

After executing the PHP Script, I am getting the following error – Any help is appreciated. Based on my understanding, I created an array based on the bugzilla documentation - Thanks in advance
https://bugzilla.readthedocs.io/en/5.0/api/core/v1/bug.html#create-bug
{"code":32000,"error":true,"message":"Could not parse the 'params' argument as valid JSON. Error: malformed number (no digits after initial minus), at character offset 1
$url ="http://localhost:8080/bugzilla/rest/bug";
$data = array(
"product" => "TestProduct",
"component" => "TestComponent",
"version" => "unspecified",
"summary" => "'This is a test bug - please disregard",
"alias" => "SomeAlias",
"op_sys" => "All",
"priority" => "P1",
"rep_platform" => "All"
);
$str_data = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array("Content-Type: application/json", "Accept: application/json"));
$username = 'ashish.sureka#in.abb.com';
$password = 'incrc';
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
$result = curl_exec($ch);
curl_close($ch);
echo $result
You have this:
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
which sends your array of data as a conventional key=value form submission, when you should have
curl_setopt($ch, CURLOPT_POSTFIELDS, $str_data);
^^^^^
which would send your JSON-encoded array instead.
You send $data in CURLOPT_POSTFIELDS but I think you need to give it $str_data which is encode in JSON
I think you have to replace
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
with
curl_setopt($ch, CURLOPT_POSTFIELDS, $str_data);
to transfer the json encoded array instead of the raw php array.

PHP - send file via curl with https

I am trying to send file via curl, but keep getting this error:
PHP Notice: Array to string conversion in /home/sasha/Documents/OffProjects/test/index.php on line 26
This is my code at the moment:
$target_url = 'https://address';
$file_name_with_full_path = realpath('mpthreetest.mp3');
$post = [
'textNote' => 'This is test',
'audioFile' => '#'.$file_name_with_full_path,
'department' => 'Test',
'timeDetected' => round(microtime(true) * 1000),
'subjectLine' => 'Test Test',
'recipients' => ['phone-number' => '111111111']
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_PORT, 443);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION, true);
$result=curl_exec ($ch);
curl_close ($ch);
echo $result;
How can I make this working?
You can't have an array as a value, it's trying to convert the post data into a string. Check what the website you are posting to is expecting for "recipients", my guess would be some form of JSON string.
When you pass an array to CURLOPT_POSTFIELDS it will try to build a form-data content (see http://php.net/manual/en/function.curl-setopt.php for details).
But you have nested arrays here:
....
'recipients' => ['phone-number' => '111111111']
...
and this cannot work. You'll have to find a different way to pass multiple values as recipients, either as a JSON string as #fire mentioned, or with a serialized value, or whatever transformation you prefer.

Why is this PHP script the JSON results when I haven't told it to?

So I'm using the only source I've found for sending a post request to Google QPX API. I want to save it in a json_decoded PHP array, but for some reason the $result = curl_exec($ch); line doesn't work, and the json prints onscreen anyways.
Is there something I'm not understanding that is happening in the cURL? Thanks!
$data = array ( "request" => array(
"passengers" => array(
adultCount => 1
),
"slice" => array(
array(
origin => "BOS",
destination => "LAX",
date => "2015-09-09"),
array(
origin => "LAX",
destination => "BOS",
date => "2015-09-10"),
),
solutions => "10"
),
);
$data_string = json_encode($data);
$ch = curl_init('https://www.googleapis.com/qpxExpress/v1/trips/search?key=MY-API-KEY');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
This:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
CURLOPT_RETURNTRANSFER - TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
http://php.net/curl_setopt
Set this option to true if you want to save the result in a variable.

POST binary file using curl

I have a basic upload form which I would like to emulate using cURL.
<?php
$params = array(
'api_key' => $api_key,
'api_secret' => $api_secret,
'urls' => null,
'uids' => 'all',
'detector' => 'Aggressive',
'namespace' => 'face.auth');
$action = $url . '?' . http_build_query($params);
?>
<form enctype="multipart/form-data" method="post" action="<?php echo $action; ?>">
<input type="file" name="upload" id="upload">
<input type="submit" />
</form>
I know how to post using cURL, but I'm not sure how to post the image data (this data is stored as binary data in a database, lets call it $binary). Passing $binary as shown below as a postfield does not work. I have seen some examples which place an # in front of the file name/path, and send that as a postfield. However, this does not appear to work for me (since I am dealing with binary data, not a file name/path).
$params = array(
'api_key' => $api_key,
'api_secret' => $api_secret,
'urls' => null,
'uids' => 'all',
'detector' => 'Aggressive',
'namespace' => 'face.auth',
$binary);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
var_dump($data);
?>
I've also tried:
$params = array(
'api_key' => $api_key,
'api_secret' => $api_secret,
'urls' => null,
'uids' => 'all',
'detector' => 'Aggressive',
'namespace' => 'face.auth');
$action = $url . '?' . http_build_query($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $action);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $binary);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
Any assistance would be appreciated.
It is not necessary to build complete data string like what #Piskvor has built in POST a file string using cURL in PHP? to achieve this...we could do this by just passing binary data in array it-self...
As curl internally does the same string building what "Piskvor" has done in above problem...
As and when curl gets array in postfield curl treats that data as "multipart/form-data"
but to achieve this we just need to do small fix in array key in which we are passing binary data...please check below you need to pass binaryData as below....and voila you will get this in $_files array on remote url
$params['image";filename="image'] = $binaryData
Now, how it was achieved:
Remote server recognize your post data for file only if it gets filename="some_name" attribute in post string built by curl....curl automatically adds this in case of #filepath but when you pass it as binary data it doesn't understands that it is file...so by that we get above binary content in post array instead of file array....
please let me know if above small change in your code doesn't works....as it worked for me...I like to share this...

Categories