Postman and cURL is returning different output - php

This is url I'm running in the postman :- http://213.252.244.214/create-signature.php. It has two parameters string and key. It will return input which you have entered and the output which is RJAGDhoz8yDJ7GwVLberI/NMYy2zMTTeR9YzXj7QhCM= but if I run it from the curl then it is returning D9UmS6r/qg0QI/0eIakifqrM3Nd1g6B3W7RCsiyO7sc=. The output is in JSON Format. Following is the cURL code:-
public function create_signature($input, $key) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://213.252.244.214/create-signature.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "string=$input&key=$key");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
$json = json_decode($output);
$signature = $json->output; echo $signature; echo '<br>';
curl_close($ch);
return $signature;
}
sample string is:- 2019-01-23 14:00:594lzUTYHw01dW5EmPan01M07hEiWUaEmdKl3kzpUUqak=Ha2wZwz46l7vSboxVNx3/DAUYsInjjKtAbDSnPsdDnA=igK7XzaTBrusPc3q5OEOQg==igK7XzaTBrusPc3q5OEOQg==1.0.110671523012111548248459fR9b/McBCzk=Deposit Fund698EURLuisTurinTurinVenis13212TF990303274103325689667lg#gmail.comLuisTurinTurinVenis13212TF990303274103325689667lg#gmail.comLuisTurinTurinVenis13212TF990303274103325689667lg#gmail.comclient_deposithttp://localhost/feature/CD-716/gateways/certus_finance/paymenthttp://localhost/feature/CD-716/gateways/certus_finance/paymenthttp://localhost/feature/CD-716/gateways/certus_finance/payment
sample key is :- 85e1d7a5e2d22e46
Can anyone tell me why is it different?? Any help will be appreciated.

Your $input and $key values are not being encoded. From the curl_setopt() manual page...
This parameter can either be passed as a urlencoded string ... or as an array with the field name as key and field data as value
Postman does this by default.
To save yourself having to manually encode strings, just use the array method
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'input' => $input,
'key' => $key
]);
Take note of this caveat though...
Note:
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.
If required, to ensure application/x-www-form-urlencoded, you can build an encoded string using http_build_query(), eg
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'input' => $input,
'key' => $key
]));

Related

Problem converting a JSON object to PHP array

Am working on a Laravel application which consumes a backend API still written in Laravel. Am passing an array of data from the frontend to the backend via curl, The data is being passed fine but on the backend/API when I try to decode it to PHP array and get an individual property in the array, I keep getting null. What could I be missing out?
PHP array am passing
$data = [
'phone' => '254712345669',
'name' => 'John Doe',
'email' => 'doejohn#email.com',
];
$token = session('access_token');
$letter = GeneralHelper::global_Curl($data , $token , 'api/v1/travel-letter');
Curl function in GeneralHelper to pass data to the backend in Json format
static function global_Curl($data, $token , $url){
$server = 'http://localhost/digital-apps-apis/public';
$headers = ["Accept:application/json",
"Content-Type:application/json",
"Authorization:Bearer ".$token
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, ($server.'/'.$url));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
$response = json_decode(curl_exec($ch));
dd($response);
curl_close($ch);
return $response;
}
API side where am retrieving the data
public function getLetter(Request $request){
return $request->all();
}
Data on the browser Network tab after returning from API side
{#368
+"phone": "254712345669"
+"name": "John Doe"
+"email": "doejohn#email.com"
}
When I decode the data so that I can get each single property I get null
public function getLetter(Request $request){
return json_decode($request->all() , true);
}
if json_decode returns null, it means that the given data is not a valid json string. the fact that in the network response the string starts with a #368 suggests me that is an object dump rather than a string. Try to double check that.
Also, probably you know that and it's a leftover form the debug but you have a dd() inside your global_Curl function

PHP Array JSON encoding and decoding in REST not working

I have the following problem. This data in this structure
$transfer = {stdClass} [4]
module = "Member"
action = "create"
token = null
params = {stdClass} [3]
username = "Test"
email = "test#test.com"
password = "Test"
has to be send vi REST to the REST Server.
Therefore I encode the data with json_encode ($object).
The decoded object looks like this:
{"module":"Member","action":"create","token":null,"params":{"username":"Test","email":"test#test.com","password":"Test"}}
For testing purpose I decode the encoded result to see if everything works fine. Which gives me the object correct back.
When I transfer the data via curl, the server receives this json_encoded data:
{"module":"Member","action":"create","token":null,"params":{"username":"Test","email":"test#test.com" = ""
And finally the json_decode($request) ands up with the following error:
json_decode() expects parameter 1 to be string, array given
The curl code for this is:
$curl = curl_init($url);
// prepare curl for Basic Authentication
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
$curl_post_data = json_encode($postdata);
$test = json_decode($curl_post_data); // for testing
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data); <= $postdata = $transfer the object/array mentioned above
$curl_response = curl_exec($curl);
curl_close($curl);
What's wrong? Why it is not possible to decode the encoded data after the curl exec to the REST Server?
This is the magic solution for that problem:
json_decode(key($object), true);
From my understanding you are sending $curl_post_data which is a json_encoded string in CURLOPT_POSTFIELDS.
CURLOPT_POSTFIELDS accepts array not a string.
So you should pass $curl_post_data['data'] = json_encode($postdata);
and receive data json_decode($request['data'])
You are facing error(json_decode() expects parameter 1 to be string, array given) because $request is blank as you passed the string

How to send and receive data to/from an API using CURL?

I have to make an API. For this, I will receive the data from the mobile devices as JSON using POST. I have to work with this data and send the response back to the devices also as JSON.
But I don't know how to take the data that I will receive. I have tried to make some tests using CURL to see how can I take this data but the $_POST is always empty. Can you please tell me how to send the data as JSON format to the API using CURL and how can I receive this data so I can work with it and send it back as response?
These are my test files:
curl.php:
//set POST variables
$url = 'http://test.dev/test.php';
$data = array(
'fname' => 'Test',
'lname' => 'TestL',
'test' => array(
'first' => 'TestFirst',
'second' => 'TestSecond'
)
);
//open connection
$ch = curl_init($url);
$json_data = json_encode($data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json_data))
);
// execute post
$result = curl_exec($ch);
echo $result;
//close connection
curl_close($ch);
test.php:
var_dump($_POST);
The response that I get is:
array(0) { }
You need to pass the POST data as a URL query string or as an array, the problem is you post data in JSON format, but PHP does not parse JSON automatically, so the $_POST array is empty. If you want it, you need do the parsing yourself in the test.php:
$raw_post = file_get_contents("php://input");
$data = json_decode($raw_post, true);
print_r($data);
same questions: 1 2

PHP cURL: circumventing '#' denoting a file POST

I'm trying to make a cURL post, and one of the parameters includes a string prefixed with the '#' symbol. Typically for a cURL post, the '#' means I'm trying post a file, but in this case, I just want to pass the string prefixed with '#'. Is there a way, or what is the best way to get around this?
Here's my params array:
$params = array(
'UserID' => $this->username,
'Password' => $this->password,
'Type' => $type,
'Symbol' => $symbol, // this will look something like #CH14
'Market' => '',
'Vendor' => '',
'Format' => 'JSN'
);
And here's how my cURL post is taking place (the url is irrelevant to the actual problem.):
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$response = curl_exec($ch);
if($response === FALSE)
{
$error = curl_error($ch);
$error_code = curl_errno($ch);
throw new Exception("CURL ERROR: #$error_code\n$error\n");
}
curl_close($ch);
return $response;
This works for everything I need it to do except when I need to pass it a symbol with an '#' in front. Any help would be greatly appreciated. Thanks.
According to the curl_setopt() manual entry:
CURLOPT_POSTFIELDS
The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with # and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. 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.
Hence, we can simply convert it to a string using http_build_query():
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
Use http_build_query() to build the query string.
From the documentation for the function:
Generates a URL-encoded query string from the associative (or indexed) array provided.
As stated above, it will correctly encode all the special characters as required. It can be used as below:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
Online demo

How to send form fields and a file using PHP Curl?

I'm trying to send form fields and file to a web service using php curl. The form has already been passed from a browser to a proxy php client web app and I'm trying to forward it to the web service.
When I pass an array to curl_setopt like this:
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $this->fields);
I get a Array to String notice although it is meant to take an array. Here's my array that is passed to $this->fields in the constructor.
$fields = array('title'=>$title,
'content'=>$content,
'category'=>$category,
'attachment'=>$_FILES['attachment']);
If I pass a string using http_build_query my web serivce complains about not having multipart/form data.
If I then force the multipart/form enctype using curl_setopt I get an error saying there's no boundary:
org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
Any ideas?
The array to string notice you have with the following code :
$fields = array(
'title'=>$title,
'content'=>$content,
'category'=>$category,
'attachment'=>$_FILES['attachment']
);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $fields);
is not because of you're passing an array as 3rd parameter to curl_setopt : it's because you're passing an array for attachment.
If you want to pass a file this way, you should pass its absolute path, pre-pending a # before it :
$fields = array(
'title'=>$title,
'content'=>$content,
'category'=>$category,
'attachment'=> '#' . $_FILES['attachment']
);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $fields);
(This is supposing that $_FILES['attachment'] contains the full path to your file -- up to you to change this code so it's using the right data, if needed)
As a reference, quoting the manual page of curl_setopt, for the CURLOPT_POSTFIELDS option :
The full data to post in a HTTP "POST" operation.
To post a file, prepend a filename with # and use the full path.
This 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.
try this,
$filePath = "abc\\xyz.txt";
$postParams["uploadfile"] = "#" . $filePath;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, 'https://website_address');
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $postParams);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
if (curl_errno($ch))
{
echo curl_error($ch);
exit();
}
curl_close($ch);

Categories