PHP Array JSON encoding and decoding in REST not working - php

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

Related

Why does my cURL fails? I'm trying to verify user identity on an API

Here are the codes:
<?php
class General{
#to verify user password with api
public static function verifyUser($user,$pswd){
#url
$url = 'https://api.hp.upm.edu.my/cron/request/verify.php';
# initiate cur
$ch = curl_init($url);
# create json data
$jsonData = array(
'jtoken' => "test123",
'id' => "$user",
'pass'=> "$pswd"
);
#Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
#Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
#Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
#Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
#Execute the request
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
}
?>
The passed data are username and password, identified by $user and $pswd respectively
The problem is, the end result should return something.
But I found it empty, after checking.
So, what I learned so far are:
I checked the user and password, they are all intact
when I print $ch during "initiate cur", it prints something
when I printed $ch
However, when I printed $result after curl_exec, it is empty.
What do I do? Where is my mistake? Is it the problem of the api url or soemthing else? Please, I need your help
Edit:
Someone suggested that using json_decode will help with this. But, I have already implemented json_decode, after $result is returned.
$result = General::verifyUser($_POST['user'], $_POST['pass']);
$obj = json_decode($result, true);
Above is the method call that passes the username and password to the "General" class.
I have printed curl_error for $ch and it says:
"Could not resolve host: api.hp.upm.edu.my"

PHP Curl Send JSON Data

I am following this tutorial:
https://lornajane.net/posts/2011/posting-json-data-with-php-curl
what I am trying to do is POST JSON Data through CURL
$url = "http://localhost/test/test1.php";
$data = array("name" => "Hagrid", "age" => "36");
$data_string = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
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);
var_dump($result);
when I POST plain text data , I am able to receive that, but when I try through JSON , I am not able to receive that.
Here is my test1.php
test1.php
print_r($_POST);
print_r($_POST);
Any help would be appreciated.
Thanks
When you POST JSON Data through cURL, you have to use php://input. You can use it like:
// get the raw POST data
$rawData = file_get_contents("php://input");
// this returns null if not valid json
return json_decode($rawData, true); // will return array
php://input is a read-only stream that allows you to read raw data
from the request body
The PHP superglobal $_POST, only is supposed to wrap data that is either
application/x-www-form-urlencoded (standard content type for simple form-posts) or
multipart/form-data-encoded (mostly used for file uploads)
The content would now be application/json (or at least none of the above mentioned), so PHP's $_POST -wrapper doesn't know how to handle that (yet).
Reference
JSON data does not come through in $_POST. You need to use file_get_contents('php://input');
You will also need to json_decode it.
$json = json_decode(file_get_contents('php://input'));
var_dump($json);

PHP - How to get POSTFIELDS sent with CURL?

I am using curl to call API method (Symfony2, FOSRestBundle) and wonder how can I get the data sent in POSTFIELDS?
$_params = [];
$data_string = json_encode($_params);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $_method);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_VERBOSE, true);
$json = curl_exec($curl);
If I send something in for example CURLOPT_HTTPHEADER I can get it later in controller using
$request->headers->get("some_variable");
But how can I access $data_string? I have dumped almost every possible variable and still nothing.
To retrieve a POST value in symphony you can use:
$request->request->get('key', 'default value');
Assuming $_params is a valid json object, you need to url-ify the data for the POST, i.e.:
$post_fields = http_build_query(json_decode($_params));
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_fields); </s>
To retrieve all post values in symphony you can use:
$params = $this->getRequest()->request->all();
$params['val1'];
$params['val2'];
As I understand your first code snippet, you're effectively trying to POST a JSON string? It was my understanding that your PHP code wouldn't work as per the PHP documentation for CURLOPT_POSTFIELDS:
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.
But as per this blog post apparently you can do it your way.
Anyway, back to your question. To get the full content of a request, you would do:
$content = $request->getContent();
And to then decode the JSON you would do:
$params = json_decode($content);
Another StackOverflow answer covers this. About the only thing I'd say is that you need to correctly set the MIME type when you're sending the post, e.g.
curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json' ]);
The previously mentioned blog post covers this.

Http post request with JSON String in PHP

Here is my code,
$url= 'http://dummyhost:8080/admin/EditSubscriber?jsonString={"sub_Id":3,"sub_Fname":"messi","sub_Lname":"lionel"}';
$data_string="";
$request = new HTTPRequest($url, HTTP_METH_POST);
$request->setRawPostData($data_string);
$request->send();
$response = $request->getResponseBody();
$response= json_decode($response, true);
at the end of url JSON string is concatenated according to server requirement
but in response there is nothing i get in response variable.
What is wrong with this as when i make this request using chrome extension it shows me the result updated. And when i use the $url= "http://dummyhost:8080/admin/ViewSubsriber?jsonString={"sub_Name":"messi","sub_Password":"password"}";
i get the desired result.
i've used curl as well'
i've used Curl as well like this
$ch = curl_init($url);
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);
curl_close($ch);
$json_result = json_decode($result, true);
but the same result i get that is nothing
If you have created JSON string at your own keep following things in mind:
Space in string might result in unnatural behavior from server so for each of the varible or atleast for strings use
urlecode(yourvariable);
then chek the string online wether the JSON string is valid or not like this
http://json.parser.online.fr/
Like Brant says use
$json = file_get_contents('php:://input');
for raw data instead of using the empty $data_string="";
Your posted variable, $data_string, is empty. You are using POST and sending empty data, but then also sending a query string. It seems you are mixing GET and POST methods here. You need to actually post your JSON string in the posted data.
If you are posting raw JSON string using application/JSON content type, the post data will need to be read from raw input like this
$json = file_get_contents('php:://input');
This is because $_POST is only automatically populated by PHP for form-encoded content types.
I would also recommend sticking with curl for such usage.

using json data from Curl response

Hi I'm a little new at CURL, but I'm trying to request some json data and then parse the results. I am having success with retrieving the data, but I can't handle the response. Here's the code
function bitBucketCurl($url)
{
global $bitPassword;
global $bitUsername;
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "$bitUsername:$bitPassword");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
$commitinfo = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
return $commitinfo;
}
$json = bitBucketCurl($url);
echo $json; // This seems to work in that, when I load the page, I can see the json data
//turn json data into an array - this is what does not seem to be working
$obj_a = json_decode($json, true);
print_r ($obj_a); //the result is simply a 1 rather than the array I would expect
The basic problem is the json data shows up when I echo $json but when I try to turn that data into an array it doesn't work. When I print the array, I just get a '1'.
I got the required result by adding the following line:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

Categories