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']);
Related
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.
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');
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.
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"}
}
Hi i am having problems with an XHR post request.
in javascript:
self.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
self.xhr.setRequestHeader("Method", "POST " + url + " HTTP/1.1");
In firebug:
Parametersapplication/x-www-form-urlencoded
{"u":"andrepadez","m":"\n...
JSON
m
"sfdsfsdfdsfdsf"
u
"andrepadez"
Source
{"u":"andrepadez","m":"\nsfdsfsdfdsfdsf"}
In .NET, I post this to an .ASHX, and in the ProcessRequest i do:
StreamReader sr = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding);
javaScriptSerializer.Deserialize<MyClass>(message);
and I have no problems.
I don't know how to get the data in PHP, either $_POST and $_REQUEST are empty arrays.
Any help please?
thanks
You've not set a field name for the data being sent. PHP requires data coming in via POST to be in a fieldname=value format. _POST is an array like any other, and every value stored in a PHP array must have a key (which is the form field name).
You can try retrieving the data by reading from php://input:
$post_data = file_get_contents('php://input');
But the simplest solution is to provide a fieldname in your XHR call.
You are setting the Content-Type to application/x-www-form-urlencoded, but you are setting the content to json. I'm guessing this is confusing your PHP webserver. Try setting your POST contents to what you tell the server it will be (application/x-www-form-urlencoded) or read the raw HTTP contents in php://input.
If you set the Content-Type to application/x-www-form-urlencoded then naturally PHP will want to parse the POST body. But as the data does not actually constitute form data, it is discarded as invalid.
You need to set the correct CT application/json (actually doesn't matter) so PHP will leave it alone. Then it becomes available as php://input or $HTTP_RAW_POST_DATA