Http post request with JSON String in PHP - 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.

Related

sending json via php curl but not getting a response

I am trying to send a json to a url and get a response back. I am creating the json correctly I believe. However when I try to send it via php curl I do not get a response back. The url I am sending it to does populate a response though.
Here is the php:
<?php
$post = array("prompt" => $question, "functionName" => $func_name, "argumentNames" => $argumentNames, "testCases" => $testCases);
$transfer = json_encode($post);
$ctrl = curl_init();
curl_setopt($ctrl, CURLOPT_URL, "https://sample.com/question/add-question.php");
curl_setopt($ctrl, CURLOPT_POST, TRUE);
curl_setopt($ctrl, CURLOPT_POSTFIELDS, $transfer);
curl_setopt($ctrl, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ctrl);
curl_close($ctrl);
$response = json_decode($response);
echo $response;
?>
If I were to echo $transfer it would read:
{
"prompt":"Write a function named test that takes 2 argument(s) and adds them. The type of the arguments passed into the function and the value to be returned is int. The arguments for the function should be arg1 and arg2 depending on the number of arguments the function needs.",
"functionName":"test",
"argumentNames":["arg1","arg2"],
"testCases":{"input":["2","2"],
"output":"4"}
}
I would like to echo the response from the url I am sending the json too but instead, I get nothing back. However the url in the curl sequence (https://sample.com/question/add-question.php) does output a json on the webpage:
{"message":"An unknown internal error occured","success":false}
How am I not able to grab this and echo it in my original code snippet? Is it something wrong with my curl method?
Try setting the header to say you are sending JSON...
curl_setopt($ctrl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($transfer))
);
For the HTTPS, you may also need...
curl_setopt($ctrl, CURLOPT_SSL_VERIFYPEER, false);
You also may try...
curl_setopt($ctrl, CURLOPT_FOLLOWLOCATION, 1);

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.

How to make a JSON Curl request to an api url, getting null

This should be simple I think but I just can't fathom it.
I need to make a request to a url in the following format:
http://ratings.api.co.uk/business/{lang}/{fhrsid}/{format} where lang will be set to en-GB the fhrsid is an identifier and format is json.
I tried the following but I am just getting null in return:
$data = array("lang" => "en-GB", "fhrsid" => "80928");
$data_string = json_encode($data);
$ch = curl_init('http://ratings.api.co.uk/business/json');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)) );
$Jsonresult = curl_exec($ch);
curl_close($ch);
var_dump(json_decode($Jsonresult));
Any help gratefully received
You are currently posting the data to the URL, while you say you want to put the data in the URL itself.
I.e. now you submit {"lang:"en-GB","fhrsid":80928} to the URL http://ratings.api.co.uk/business/json, but instead you want to retrieve the URL http://ratings.api.co.uk/business/en-GB/80928/json.
Don't use POST as request type, don't specify postfields, don't specify content-length, and do put the data in your URL.
Sending data as arguments is different than sending it within the URL.
If you require a url format of http://ratings.api.co.uk/{lang}/{fhrsid}/{format}, then you must make your curl_init string match that format.

Type of "application/json" prevents post variables from being sent

I've found that if I try a PHP POST curl, the postvars are sent fine. Once I add the httpheader of content-type: application/json the postvars don't go across any more. I've tried the postvars as a JSON string and as a query string.
Showing some code:
$ch = curl_init();
$post = json_encode(array('p1' => 'blahblahblah', 'p2' => json_encode(array(4,5,6))));
$arr = array();
array_push($arr, 'Content-Type: application/json; charset=utf-8');
curl_setopt($ch, CURLOPT_HTTPHEADER, $arr);
curl_setopt($ch, CURLOPT_URL, 'https://example.com/file.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_exec($ch);
curl_close($ch);
A real HTTP Post, that gets broken into an array automagically by PHP must be formatted in name=value pairs, the best way to do this in PHP is using the http_build_query function.
http://ca2.php.net/manual/en/function.http-build-query.php
There is an example that works in the PHP Manual using curl:
http://ca2.php.net/manual/en/function.curl-exec.php#98628
What you're doing is a 'RAW' post, see this other question:
How to post JSON to PHP with curl
A quick snippet to get the RAW Json data.
<?php
print_r(json_decode(file_get_contents('php://input')));

Categories