Pulling a base64 encoded string from http request in php - 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).

Related

Get and Send file with PHP and RESTful API

One of my partners has an API service which should send an HTTP POST request whenever a new file is published. This requires me to have an api file which will get the POST this way:
http://myip:port/api/ReciveFile
and requesting that the JSON format request should be:
{
"FILE ":"filename.zip",
"FILE_ID":"123",
"FILE_DESC":"PRUPOUS_FILE",
"EXTRAVAR":"",
"EXTRAVAR2":"",
"USERID":" xxxxxxxxxxxx",
"PASSWORD":"yyyyyyyyyyy"
}
Meanwhile it should issue a response, in JSON format if it got the file or not
{"RESULT_CODE":0,"RESULT_DESCR":""}
{"RESULT_CODE":1001,"RESULT_DESCR":"Bad request"}
And after, when I am finished elaborating the file, I should send back the modified file same way.
The question is, now basically from what I understand he will send me the variables witch I have to read, download the file, and send a response back.
I am not really sure how to do this any sample code would be welcomed!
I'm not sure exactly what the question is, but if you mean creating a success response in JSON for if an action occurred while adding data to it which is what can be understood from the question, just create an array with the values you wish to send back to the provider and do json_encode on the array which should create json and just print it back as a response.
About receiving the information; all you have to do is use the integrated curl functions or use a wrapper (Guzzle, etc) to output the raw JSON or json_decode data into a variable and do whatever you please with it.
From what I read in the question, you wish to modify the contents of it. This can be achieved by just decoding the json and changing the variables in the array, then printing the modified JSON back as a response.
Example (this uses GuzzleHTTP as an example):
$res = $client->request('GET', 'url');
$json = $res->getBody();
$array = json_decode($json, 1); // decode the json
// Start modifying the values or adding
$array['value_to_modify'] = $whatever;
$filename = $array['filename']; // get filename
// make a new request
$res = $client->request('GET', 'url/'.$filename);
// get the body of specified filename
$body = $res->getBody();
// Return the array.
echo json_encode($body);
References:
http://docs.guzzlephp.org/en/latest/

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

PHP $_POST is empty, but HTTP_RAW_POST_DATA has all data

I'm just trying to send a POST request with JS to server. But server has empty $_POST array. I could use HTTP_RAW_POST_DATA, but it'll be deprecated in PHP 5.6. Could I have posted data in my $_POST array?
Environment: Chrome, apache2, PHP, AngularJS (I'm using $http.post function).
Debug image (sorry for not attaching image directly - I have no 10 reputation)
The POST data must be in query string or multipart/form-data format to get decoded properly. Your data seems to be JSON, so you have to decode it by yourself:
$_POST = json_decode(file_get_contents('php://input'), true);
$_POST is populated by a request that is of type form-urlencoded or multipart/form-data. Typically it looks like:
foo=bar&ipsum=lorm
So kinda like a GET request.
Since you're posting JSON directly (which is awesome!) you can use:
$request_payload = file_get_contents("php://input");
See the docs for more info.
See by default, jQuery transmits data using Content-Type: x-www-form-urlencoded and the familiar foo=bar&baz=moe serialization. AngularJS, however, transmits data using Content-Type: application/json and { "foo": "bar", "baz": "moe" } JSON serialization, which unfortunately some Web server languages—notably PHP—do not unserialize natively.
so you can do this when you define your angular module:
angular.module('MyModule', [], function($httpProvider) {
// Use x-www-form-urlencoded Content-Type
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
});
answer taken from this post by Felipe Miosso.
looks like json data posting directly without any variable try with
$request = file_get_contents('php://input');
print_r($request);
or use a variable on posting data like
data{'myvar': data}
and will get on POST data like
print_r($_POST['myvar']);

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"}
}

Send json as request body or POST json in a variable

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.

Categories