Issue reading HTTP request body from a JSON POST in PHP [duplicate] - php

This question already has answers here:
Receive JSON POST with PHP
(12 answers)
Closed 12 months ago.
I'm writing a script that is registered as an endpoint for a webhook. I know that it's successfully registered because I'm writing the header of every request to my server logs. Here's a sample:
Content-Type: text/xml; charset=UTF-8
User-Agent: Jakarta Commons-HttpClient/3.1
Host: =={obfuscated}==
Content-Length: 1918
The API that I've registered with is POST-ing a JSON object to my script, and I'd like to parse that object using PHP. As you can see from the request header, there's a nice big fat JSON object waiting to be parsed. It seems straightforward, but it hasn't been.
At first I tried using $_POST['json'] or just $_POST but since the data isn't in an array, I wasn't really sure how to access it like that.
I've tried using file_get_contents('php://input') and fopen('php://input', 'r') with and without json_decode() but no luck. I can't use http_get_request_body() since the server I'm on doesn't have PECL and that's out of my control.
Are there any other ways to interact with the POST-ed JSON object that I'm missing? Thanks!

It turns out that I just needed
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); //convert JSON into array
where the second parameter in json_decode returned the object as an array.

Even when the following works.
$inputJSON = file_get_contents('php://input');
If you want to continue using $_POST send the data as FormData
var fd = new FormData();
fd.append('key', 'value');
return axios.post('url', fd)

Related

Read Angular2 POST data in PHP [duplicate]

This question already has answers here:
Reading JSON POST using PHP
(3 answers)
Closed 6 years ago.
I want to connect my angular2 app to my PHP backend. Ideally I want to do this:
this.http.post('/users/create', {email: email, password: password});
The problem is, when I do this my $_POST is empty in PHP. What must I do to make this work?
Angular's http implementation sends data as an application/json payload. to read such data from php, you have to use this kind of code :
$data = json_decode(file_get_contents("php://input"));
// you can even override the `$_POST` superglobal if you want :
$_POST = json_decode(file_get_contents("php://input"));
if you want to send your data as application/x-www-form-urlencoded and then be able to read it from php's $_POST superglobal without any change to your server code, you need to encode your data as such.
const body = new URLSearchParams();
Object.keys(value).forEach(key => {
body.set(key, value[key]);
}
let headers = new Headers();
headers.append('Content-Type','application/x-www-form-urlencoded');
this._http.post(this._contactUrl, body.toString(), {headers}).subscribe(res => console.log(res));
I mean with jQuery for example it works with $_POST and json objects
it does not work with json object, if you can read data via $_POST, it means it has been sent as application/x-www-form-urlencoded, not application/json, parameters are set as a plain js object though...
you can use php://input for the post data with angular2 like this and json_decode by this
$arr = json_decode(file_get_contents('php://input'),TRUE);
echo "<pre>";print_r($arr);exit;
so by this $arr prints the whole post array and used it anywhere you want.

How to read JSON data using PHP [duplicate]

This question already has answers here:
Reading JSON POST using PHP
(3 answers)
Closed 7 years ago.
I am trying to read data send by curl request but I cant able to read that.
example
curl -x post -d '{user:"test", pwd:"123"}' http://localhost/api/login/
and in PHP code
$user = $_POST['user'];
but always I am getting a null value, how to fix this issue?
You can specify the post name in curl. Right now you're submitting JSON, but without a name. (Link to curl man pages)
-d data={JSON}
Then in php you can load and decode the JSON: (Link to json_decode in the php manual)
$data = json_decode($_POST['data'], true);
$user = $data['user'];
If you want to continue sending data without using key/value pairs, you can keep your existing implementation of curl and use the following in PHP:
$data = #file_get_contents("php://input");
$json = json_decode($data, true);
This was taken from: XMLHTTP request passing JSON string as raw post data

How to get external JSON with PHP that has content-type text/plain?

I am trying to fetch an external JSON response with my PHP back-end
But my problem is that the external endpoint is returned as the Content-Type: text/plain;charset=utf-8, and that only gives me gibberish when I read it.
string '����������ݒ�J�� ... etc...
Is there a way to encode that response?
This is what I have done:
$response = file_get_contents('external_url');
I have also tried this:
$json = json_decode(file_get_contents('external_url'), true);
It doesn't really matter to PHP what Content-Type the response declares, it doesn't do anything with that information. You're getting exactly the same response body whether the header says text/plain or JSON.
More likely the response is compressed and you need to uncompress it with gzinflate or such.

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

Categories