How to properly format body for post request?
Solution 1
okay, got it working, here is what is needed
two content types:
Content-Type: application/json
Content-Type: application/x-www-form-urlencoded
and then set your params like so in body:
param1=value1¶m2=value2
Thanks for the help everyone.
Solution 2
PHP will not parse a JSON body automatically into the $_POST
superglobal. That only happens with application/x-www-form-urlencoded
and multipart/form-data
POST bodies. That said, you can parse the body yourself — you can access the raw POST body via the php://input
pseudo-stream.
Rob
Updated on July 05, 2022Comments
-
Rob almost 2 years
I'm using a firefox pluing called restclient to simulate a post request. It doesnt' seem to be picking up any post data, but not sure if I'm formatting it properly.
using header: Content-Type: application/json and body: {"id":1234}
but not go, it's not picking up the id parameter in my php, is there some special formatting I need to set?
-
Rob almost 12 yearsok, i'ave added Content-Type:application/x-www-form-urlencoded, still no go, am I missing something else? I just want to simulate a POST request.
-
lanzz almost 12 yearsYes. Your actual body content is JSON, it is not enough to just lie the server about what you're sending. You either have to actually encode the body in
application/x-www-form-urlencoded
format, or you need to handle the JSON explicitly on the backend. -
Quasdunk almost 12 yearsThis might work, but is not really correct. Your content can't have several types. It's just one type which in this case is
Content-Type: application/x-www-form-urlencoded
. JSON looks something like{'key1':'value1','key2':'value2','key3':'value3'}
, and if you had that you would have to set the header toContent-Type: application/json
. Appearently, now your server simply picks the last header. But this example should also work if you omit the misleading one, since it is not JSON. -
Quasdunk almost 12 yearsSo, when working with url-encoded key-value pairs like
param1=value1¶m2=value2
, the correct Content-Type isapplication/x-www-form-urlencoded
and you can access it through the$_POST
-array on the server side. If you have JSON data like{'key1':'value1','key2':'value2','key3':'value3'}
, set the content-type toapplication/json
and you can turn the data into an array on the server side with$data_array = json_decode(file_get_contents('php://input'), true);