Send json as request body or POST json in a variable - php

I am trying to figure out, is there any way of sending raw json to php instead of POST parameter. If it is possible then which way is best i mean either request body or POST parameter.

Send an HTTP request which has a JSON string as its request body (here: using curl on the command line):
$ curl -d '{"foo":"bar"}' example.com/test.php
Read this request body in PHP:
$json = file_get_contents('php://input');
Decode it:
$data = json_decode($json, true);
PHP's $_POST superglobal is automatically populated as an array if the request body of a POST request contains URL encoded key-value pairs (e.g. foo=bar&baz=42). In the above example you're still using an HTTP POST request with "POST data". It just doesn't automatically end up in $_POST because PHP doesn't know how to decode JSON automagically.

Related

Difference between file_get_contents and $ _POST

I'm sending data through POST from one application to another, using the file_get_contents function, I can't receive the data but using the variable $ _POST I can get it. Which would be the most suitable to receive the data?
I would like to send a token for authentication together, how could I do that?
$cont = json_decode(file_get_contents('php://input'), true);
echo gettype($cont);
NULL
And when I try the pre-defined variable, I can receive the data.
$cont = $_POST;
echo gettype($cont);
array
file_get_contents('php://input') gets the raw POST data as a string.
$_POST gets the POST data after PHP has automatically decoded it from application/x-www-form-urlencoded or multipart/form-data encodings.
If the data isn't encoded using one of those methods (e.g. if it is JSON as per your first example which uses json_decode) then $_POST won't be populated.

Reading Request Payload in PHP

How can I read content of Request Payload (POST) using PHP?
I´m using a Angular aplication to send the POST.
I've tried with: $_POST, $_FILES and file_get_contents('php://input') ...
None worked.
If you need view x-www-form-urlencoded post data, just use
print_r($_POST);
If you need view json post data, use this
$data=json_decode(file_get_contents('php://input'),1);
print_r($data);
Try:
$payload = file_get_contents('php://input');

Pulling a base64 encoded string from http request in php

Background
I wrote a small test to make sure I could pull the data from a POST request made from my mobile application. It works fine,
$rawJsonObj = file_get_contents('php://input');
$json = json_decode( $rawJsonObj, true );
$decodedData = base64_decode($json['data']);
file_put_contents('student-data/'.$json['username'].'.txt', $decodedData);
Then in my Slim Framework app I try the same logic and the actual data that I use to create the file with is null. But I can still access the username and password that are sent in the request.
$app->post('/api/v1/endpoint', function ($request, $response, $args) {
$rawJsonObj = $request->getParams();
$json = json_decode( $rawJsonObj, true );
$decodedData = base64_decode($json['data']);
file_put_contents('test.txt', $decodedData);
return $response;
}
The username and password are showing in the request and I can see them when I write the data in the request to a file.
$data = $request->getParams();
file_put_contents('2.txt', $data);
Data that is wrote to file,
","username":"myuname","password":"myPword"}
But the base64encoded string is missing,
Example
In Swift I am creating the dict like this, then POST it as json,
let dict: [String: Any] = [
"username": named,
"password": password,
"data": data.base64EncodedString()
]
if let json = try? JSONSerialization.data(withJSONObject: dict, options: []) {
request.httpBody = json
}
Question
How do I access the actual "data": data.base64EncodedString() from the request body in Slim Framework 3?
I assume this has to do with the way $rawJsonObj = file_get_contents('php://input'); actually handles the data compared to Slim?
Request::getParams() is a custom method by Slim (not part of PSR-7) that collects all input data; in other words, it's a rough equivalent of PHP's $_REQUEST superglobal. Internally, it grabs the request body with Request::getParsedBody() (this one, part of PSR-7). Here's where major differences with $_REQUEST or $_POST arise:
If the request Content-Type is either
application/x-www-form-urlencoded or multipart/form-data, and the
request method is POST, this method MUST return the contents of
$_POST.
Otherwise, this method may return any results of deserializing the
request body content; as parsing returns structured content, the
potential types MUST be arrays or objects only. A null value
indicates the absence of body content.
While $_POST only decodes standard form encodings (thus in your test code you need to fetch and parse data manually) getParsedBody() tries to decode other encodings but, just like $_POST, it needs a proper Content-Type to do so. If you send one from your mobile app:
Content-Type: application/json
... it'll work as expected because Slim has a builtin JSON decoder.
If you can't send an encoding declaration, you need to decode stuff manually. In this case, the PSR-7 way to fetch the raw request body is Message::getBody(), that returns a stream (more specifically, a Stream object that that implements StreamInterface).

How to access a JSON request body of a POST request in Slim?

I'm just a newbie in the Slim framework. I've written one API using Slim framework.
A POST request is coming to this API from an iPhone app. This POST request is in JSON format.
But I'm not able to access the POST parameters that are sent in a request from iPhone. When I tried to print the POST parameters' values I got "null" for every parameter.
$allPostVars = $application->request->post(); //Always I get null
Then I tried to get the body of a coming request, convert the body into JSON format and sent it back as a response to the iPhone. Then I got the parameters' values but they are in very weird format as follows:
"{\"password\":\"admin123\",\"login\":\"admin#gmail.com\",\"device_type\":\"iphone\",\"device_token\":\"785903860i5y1243i5\"}"
So one thing for sure is POST request parameters are coming to this API file. Though they are not accessible in $application->request->post(), they are coming into request body.
My first issue is how should I access these POST parameters from request body and my second issue is why the request data is getting displayed into such a weird format as above after converting the request body into JSON format?
Following is the necessary code snippet:
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
//Instantiate Slim class in order to get a reference for the object.
$application = new \Slim\Slim();
$body = $application->request->getBody();
header("Content-Type: application/json");//setting header before sending the JSON response back to the iPhone
echo json_encode($new_body);// Converting the request body into JSON format and sending it as a response back to the iPhone. After execution of this step I'm getting the above weird format data as a response on iPhone.
die;
?>
Generally speaking, you can access the POST parameters individually in one of two ways:
$paramValue = $application->request->params('paramName');
or
$paramValue = $application->request->post('paramName');
More info is available in the documentation: http://docs.slimframework.com/#Request-Variables
When JSON is sent in a POST, you have to access the information from the request body, for example:
$app->post('/some/path', function () use ($app) {
$json = $app->request->getBody();
$data = json_decode($json, true); // parse the JSON into an assoc. array
// do other tasks
});
"Slim can parse JSON, XML, and URL-encoded data out of the box" - http://www.slimframework.com/docs/objects/request.html under "The Request Body".
Easiest way to handle a request in any body form is via the "getParsedBody()". This will do guillermoandrae example but on 1 line instead of 2.
Example:
$allPostVars = $application->request->getParsedBody();
Then you can access any parameters by their key in the array given.
$someVariable = $allPostVars['someVariable'];
Slim will json_decode the post body for you using this middleware
https://www.slimframework.com/docs/v4/middleware/body-parsing.html

Can't read raw POST body data - how to do this in this example?

I'm setting an API for my server for another developer. I'm currently using Flash AIR to send POST data to my server, and simply extract the variables as in
$command = $_POST['command'].
However, he's not using Flash, and is sending data like so:
https://www.mysite.com POST /api/account.php?command=login HTTP/1.1
Content-Type: application/json
Connection: close
command=login
params {"pass":"12345678","token":"","appID":"theirApp","user":"johnnyb","ver":"2.0","Library_ID":"1"}
My server is returning him an error saying that the 'command' parameter is missing.
What do I need to do my end to extract the $_POST var 'command' from his above data?
I've tried file_get_contents('php://input') and http_get_request_body(), but although they don't error, they don't show anything.
Thanks for your help.
The request claims that it is sending JSON.
Content-Type: application/json
However, this:
command=login
params {"pass":"12345678","token":"","appID":"theirApp","user":"johnnyb","ver":"2.0","Library_ID":"1"}
… is not JSON.
If you get rid of everything before the { then it would be JSON and you should be able to read it with file_get_contents('php://input') (and could then pass it through a decoder.
I've tried file_get_contents('php://input') and http_get_request_body() … they don't show anything.
They should work.
When I print out file_get_contents('php://input') for the comms … I get command=login, yet...
I thought you said you didn't get anything
if(!isset($_POST['command']))
$_POST will only be populated for the two standard HTML form encoding methods. If you are using JSON then it won't be automatically parsed, you have to do it yourself (with valid JSON input (so the additional data would need to be encoded in the JSON text with the rest of the data)), file_get_contents('php://input') and decode_json).
"Content-Type should be www-form-urlencoded" from #Cole (correct answer)
More info here: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1
The command parameter needs to be part of the data, and the whole thing should be valid JSON. As is, command=login, it is not valid JSON.
Add it to the params object or make a containing object, like
{
command:'login',
params :{"pass":"12345678","token":"","appID":"theirApp","user":"johnnyb","ver":"2.0","Library_ID":"1"}
}

Categories