Hobroker
Hobroker

Reputation: 380

How to get "php://input" data if I'm using Content-Type multipart/form-data

Is there an alternative?

I'm using Advanced Rest Client for testing an API I'm developing.

I send a JSON with POST. In code, $_FILES is fine, but file_get_contents("php://input") is empty.

If I don't send any files, then I can use file_get_contents("php://input")

PHP version: 5.6.4

Upvotes: 6

Views: 8181

Answers (4)

Hobroker
Hobroker

Reputation: 380

Ok, so I ended up giving a name to my JSON data, like 0=[{"q":"w"}] and then get it with $_POST['0']. And the files with $_FILES

Here's how it looks in Advanced REST Client: enter image description here

Upvotes: 1

Robert
Robert

Reputation: 5973

As GhostGambler states, php://input is not available with enctype="multipart/form-data".

You should not attach the JSON as a file to your request, you should add it as the request body to the post request, setting the Content-Type header (application/json). Then it will be available in php://input.

Upvotes: 4

Ulrich Thomas Gabor
Ulrich Thomas Gabor

Reputation: 6654

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".

http://php.net/manual/de/wrappers.php.php

Since HTTP_RAW_POST_DATA is marked deprecated, I guess you are somewhat unlucky. I do not know alternatives.

Edit: Well, you could try php://stdin / STDIN, although I do not know if this works with PHP in a webserver ... maybe just try it out.

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318698

Most likely accessing any of the POST/FILES superglobals consumes php://input.

In any case, if you send a JSON payload you cannot have a multipart-formdata payload too so $_FILES should be empty. If you need to handle both on the same page (bad idea IMO) make sure to check the content type header or some other information outside the request's body before accessing either $_FILES or php://input

Upvotes: 0

Related Questions